Top 20 Core Java Interview Questions and Answers Asked on Investment Banks

download Top 20 Core Java Interview Questions and Answers Asked on Investment Banks

of 14

description

Java Interview Questions and Answers

Transcript of Top 20 Core Java Interview Questions and Answers Asked on Investment Banks

  • Top 20 Core Java Interview Questions and Answers asked on Investment Banks

    http://javarevisited.blogspot.com/2011/04/top-20-core-java-interview-questions.html[8/3/2014 3:08:01 PM]

    T H U R S D A Y , A P R I L 7 , 2 0 1 1

    Top 20 Core Java Interview Questions and Answers asked on Investment Banks

    Core Java Interview Question AnswerThis is a new series of sharing core Java interview question and answer on Finance domain and mostly on bigInvestment bank.Many of these Java interview questions are asked on JP Morgan, Morgan Stanley, Barclaysor Goldman Sachs. Banks mostly asked core Java interview questions from multi-threading, collection,serialization, coding and OOPS design principles. Anybody who is preparing for any Java developer Interviewon any Investment bank can be benefited from these set of core Java Interview questions and answers. I havecollected these Java questions from my friends and I thought to share with you all. I hope this will be helpful forboth of us. It's also beneficial to practice some programming interview questions because in almost all Javainterview, there is at-least 1 or 2 coding questions appear. Please share answers for unanswered Java interviewquestions and let us know how good these Java interview questions are?

    These Java interview questions are mix of easy, tough and tricky Java questions e.g. Why multiple inheritance isnot supported in Java is one of the tricky question in java. Most questions are asked on Senior and experiencedlevel i.e. 3, 4, 5 or 6 years of Java experience e.g. How HashMap works in Java, which is most popular onexperienced Java interviews. By the way recently I was looking at answers and comments made on Javainterview questions given in this post and I found some of them quite useful to include into main post to benefitall. By the way apart from blogs and articles, you can also take advantage of some books, which are especiallywritten for clearing any programming interviews and some focused on Java programming, two books whichcomes in minds are programming interview exposed and Java/J2EE interview companion from fellow bloggerArulkumaran. Former is focused on programming in general and lot of other related topics e.g. data structures,algorithms, database, sql, networking and behavioral questions, while later is completely dedicated to Java J2EEconcepts.

    Core Java Interview Questions Answers in Finance domain

    1. What is immutable object? Can you write immutable object?Immutable classes are Java classes whose objects can notbe modified once created. Any modification in Immutableobject result in new object. For example String is immutablein Java. Mostly Immutable classes are also final in Java, inorder to prevent sub classes from overriding methods, whichcan compromise Immutability. You can achieve samefunctionality by making member as non final but private andnot modifying them except in constructor. Apart form obvious,you also need to make sure that, you should not exposeinternals of Immutable object, especially if it contains amutable member. Similarly, when you accept value formutable member from client e.g. java.util.Date, use

    clone() method keep separate copy for yourself, to prevent risk of malicious client modifying mutable referenceafter setting it. Same precaution needs to be taken while returning value for a mutable member, return anotherseparate copy to client, never return original reference held by Immutable class. You can see my post How tocreate Immutable class in Java for step by step guide and code examples.

    2. Does all property of immutable object needs to be final?Not necessary, as stated above you can achieve same functionality by making member as non final but privateand not modifying them except in constructor. Don't provide setter method for them and if it is a mutable object,then don't ever leak any reference for that member. Remember making a reference variable final, only ensuresthat it will not be reassigned a different value, but you can still change individual properties of object, pointed bythat reference variable. This is one of the key point, Interviewer like to hear from candidates. See my post onJava final variables, to learn more about them.

    3. What is the difference between creating String as new() and literal?When we create string with new() Operator, its created in heap and not added into string pool while Stringcreated using literal are created in String pool itself which exists in PermGen area of heap.

    String str = new String("Test");

    does not put the object str in String pool , we need to call String.intern() method which is used to put

  • Top 20 Core Java Interview Questions and Answers asked on Investment Banks

    http://javarevisited.blogspot.com/2011/04/top-20-core-java-interview-questions.html[8/3/2014 3:08:01 PM]

    them into String pool explicitly. its only when you create String object as String literal e.g. String s = "Test"Java automatically put that into String pool. By the way there is a catch here, Since we are passing argumentsas "Test", which is a String literal, it will also create another object as "Test" on string pool. This is the onepoint, which has gone unnoticed, until knowledgeable readers of Javarevisited blog suggested it.

    4. How does substring () inside String works?Another good Java interview question, I think answer is not sufficient but here it is Substring creates new objectout of source string by taking a portion of original string. This question was mainly asked to see if developer isfamiliar with risk of memory leak, which substring can create. Until Java 1.7, substring holds reference of originalcharacter array, which means even a substring of 5 character long, can prevent 1GB character array fromgarbage collection, by holding a strong reference. This issue is fixed in Java 1.7, where original character arrayis not referenced any more, but that change also made creation of substring bit costly in terms of time. Earlier itwas on the range of O(1), which could be O(n) in worst case on Java 7. See my post How SubString works inJava for detailed answer of this Java question.

    5. Which two method you need to implement to use an Object as key in HashMap ?In order to use any object as Key in HashMap or Hashtable, it must implements equals and hashcode method inJava. Read How HashMap works in Java for detailed explanation on how equals and hashcode method is usedto put and get object from HashMap. You can also see my post 5 tips to correctly override equals in Java tolearn more about equals.

    6. Where does equals and hashcode method comes in picture during get operation?This core Java interview question is follow-up of previous Java question and candidate should know that onceyou mention hashCode, people are most likely ask, how they are used in HashMap.When you provide key object,first it's hashcode method is called to calculate bucket location. Since a bucket may contain more than one entryas linked list, each of those Map.Entry object are evaluated by using equals() method to see if they containthe actual key object or not. See How HashMap works in Java for detailed explanation.

    7. How do you handle error condition while writing stored procedure or accessing stored procedure fromjava?This is one of the tough Java interview question and its open for all, my friend didn't know the answer so hedidn't mind telling me. My take is that stored procedure should return error code if some operation fails but ifstored procedure itself fail than catching SQLException is only choice.

    8. What is difference between Executor.submit() and Executer.execute() method ?This Java interview question is from my list of Top 15 Java multi-threading question answers, Its getting popularday by day because of huge demand of Java developer with good concurrency skill. Answer of this Javainterview question is that former returns an object of Future which can be used to find result from workerthread)

    By the way @vinit Saini suggested a very good point related to this core Java interview question

    There is a difference when looking at exception handling. If your tasks throws an exception and if it wassubmitted with execute this exception will go to the uncaught exception handler (when you don't haveprovided one explicitly, the default one will just print the stack trace to System.err). If you submitted thetask with submit any thrown exception, checked exception or not, is then part of the task's return status.For a task that was submitted with submit and that terminates with an exception, the Future.get will re-throw this exception, wrapped in an ExecutionException.

    9. What is the difference between factory and abstract factory pattern?This Java interview question is from my list of 20 Java design pattern interview question and its open for all ofyou to answer.@Raj suggested

    Abstract Factory provides one more level of abstraction. Consider different factories each extended froman Abstract Factory and responsible for creation of different hierarchies of objects based on the type offactory. E.g. AbstractFactory extended by AutomobileFactory, UserFactory, RoleFactory etc.Each individual factory would be responsible for creation of objects in that genre.

    You can also refer What is Factory method design pattern in Java to know more details.

  • Top 20 Core Java Interview Questions and Answers asked on Investment Banks

    http://javarevisited.blogspot.com/2011/04/top-20-core-java-interview-questions.html[8/3/2014 3:08:01 PM]

    10. What is Singleton? is it better to make whole method synchronized or only critical sectionsynchronized ?Singleton in Java is a class with just one instance in whole Java application, for example java.lang.Runtimeis a Singleton class. Creating Singleton was tricky prior Java 4 but once Java 5 introduced Enum its very easy.see my article How to create thread-safe Singleton in Java for more details on writing Singleton using enum anddouble checked locking which is purpose of this Java interview question.

    11. Can you write critical section code for singleton?This core Java question is followup of previous question and expecting candidate to write Java singleton usingdouble checked locking. Remember to use volatile variable to make Singleton thread-safe. check 10 Interviewquestions on Singleton Pattern in Java for more details and questions answers

    12. Can you write code for iterating over hashmap in Java 4 and Java 5 ?Tricky one but he managed to write using while and for loop.Actually there are four ways to iterate over any Map in Java, oneinvolves using keySet() and iterating over key and then usingget() method to retrieve values, which is bit expensive. Secondmethod involves using entrySet() and iterating over them eitherby using foreach loop or while with Iterator.hasNext()method. This one is better approach because both key and valueobject are available to you during Iteration and you don't need tocall get() method for retrieving value, which could give O(n)performance in case of huge linked list at one bucket. See mypost 4 ways to iterate over Map in Java for detailed explanationand code examples.

    13. When do you override hashcode and equals() ?Whenever necessary especially if you want to do equality check based upon business logic rather than objectequality e.g. two employee object are equal if they have same emp_id, despite the fact that they are twodifferent object, created by different part of code. Also overriding both these methods are must if you want to usethem as key in HashMap. Now as part of equals-hashcode contract in Java, when you override equals, youmust overide hashcode as well, otherwise your object will not break invariant of classes e.g. Set, Map whichrelies on equals() method for functioning properly. You can also check my post 5 tips on equals in Java tounderstand subtle issue which can arise while dealing with these two methods.

    14. What will be the problem if you don't override hashcode() method ?If you don't override equals method, than contract between equals and hashcode will not work, according towhich, two object which are equal by equals() must have same hashcode. In this case other object may returndifferent hashcode and will be stored on that location, which breaks invariant of HashMap class, because theyare not supposed to allow duplicate keys. When you add object using put() method, it iterate through allMap.Entry object present in that bucket location, and update value of previous mapping, if Map alreadycontains that key. This will not work if hashcode is not overridden. You can also see my post on tips to overridehashcode in Java for more details.

    15. Is it better to synchronize critical section of getInstance() method or whole getInstance() method?Answer is only critical section, because if we lock whole method than every time some some one call thismethod, it will have to wait even though we are not creating any object. In other words, synchronization is onlyneeded, when you create object, which happens only once. Once object has created, there is no need for anysynchronization. In fact, that's very poor coding in terms of performance, as synchronized method reduceperformance upto 10 to 20 times. By the way, there are several ways to create thread-safe singleton in Java,which you can also mention as part of this question or any follow-up.

    16. What is the difference when String is gets created using literal or new() operator ?When we create string with new() operator, its created in heap only and not added into string pool, while Stringcreated using literal are created in String pool itself which exists in PermGen area of heap. You can put suchstring object into pool by calling intern() method. If you happen to create same String object multiple times,intern() can save some memory for you.

    17. Does not overriding hashcode() method has any performance implication ?This is a good question and open to all , as per my knowledge a poor hashcode function will result in frequentcollision in HashMap which eventually increase time for adding an object into Hash Map.

    18. Whats wrong using HashMap in multithreaded environment? When get() method go to infinite loop ?

  • Top 20 Core Java Interview Questions and Answers asked on Investment Banks

    http://javarevisited.blogspot.com/2011/04/top-20-core-java-interview-questions.html[8/3/2014 3:08:01 PM]

    Well nothing is wrong, it depending upon how you use. For example if you initialize the HashMap just by onethread and then all threads are only reading from it, then it's perfectly fine. One example of this is a Map whichcontains configuration properties. Real problem starts when at-least one of those thread is updating HashMapi.e. adding, changing or removing any key value pair. Since put() operation can cause re-sizing and which canfurther lead to infinite loop, that's why either you should use Hashtable or ConcurrentHashMap, later is better.

    19. Give a simplest way to find out the time a method takes for execution without using any profilingtool?this questions is suggested by @MohitRead the system time just before the method is invoked and immediately after method returns. Take the timedifference, which will give you the time taken by a method for execution.

    To put it in code

    long start = System.currentTimeMillis ();method ();long end = System.currentTimeMillis ();

    System.out.println (Time taken for execution is + (end start));

    Remember that if the time taken for execution is too small, it might show that it is taking zero milliseconds forexecution. Try it on a method which is big enough, in the sense the one which is doing considerable amount ofprocessing

    20. How would you prevent a client from directly instantiating your concrete classes? For example, youhave a Cache interface and two implementation classes MemoryCache and DiskCache, How do you ensurethere is no object of this two classes is created by client using new() keyword.

    I leave this ququestion for you to practice and think about, before I give answer. I am sure you can figure outright way to do this, as this is one of the important decision to keep control of classes in your hand, greatfrom maintenance perspective.

    Recommended Books to prepare Java Interviews

    Apart from blogs and articles, you can also take help of some books, which are especially written to help withprogramming interviews, covering wide range of questions starting from object oriented design, coding, Java basicconcepts, networking, database, SQL, XML and problem solving skills. Following books are from my personal collection,which I often used to revise before going for any interview.

    Programming Interviews Exposed: Secrets to Landing Your Next Job

    Cracking the Coding Interview: 150 Programming Questions and Solutions

    Java/J2EE Job Interview Companion by Arulkumaran KumaraswamipillaiElements of Programming Interviews: 300 Questions and Solutions

  • Top 20 Core Java Interview Questions and Answers asked on Investment Banks

    http://javarevisited.blogspot.com/2011/04/top-20-core-java-interview-questions.html[8/3/2014 3:08:01 PM]

    all answers related to singletons in Java seem to ignore the "double-checked locking is broken" problem; it isbest to initialize the single instance in the class initializer.

    private final SingletonClass INSTANCE = new SingletonClass();

    April 11, 2011 at 7:23 PM

    Javin Paul said...

    Thanks Job good to know that these java interview questions are useful for you.

    April 15, 2011 at 7:49 PM

    Javin Paul said...

    Thanks a lot Anonymous for informing us about subtle details about Substring() method , I guess Interviewerwas looking for that information in his question "How does substring () inside String works?" because ifsubstring also shares same byte array then its something to be aware of.

    April 15, 2011 at 7:51 PM

    Javin Paul said...

    Hi Scott,your solution is correct but with the advent of java 5 and now guarantee of volatile keyword and change inJava memory model guarantees that double checking of singleton will work. another solution is to use EnumSingeton. you can check my post about Singleton here Singleton Pattern in Java

    April 15, 2011 at 7:53 PM

    Javin Paul said...

    Hi Anand,Thanks for answering question "How does substring () inside String works?"

    April 15, 2011 at 7:54 PM

    emt said...

    Use can use a static holder to handle the singleton creation instead of double checked mechanism.

    public class A {private static class Holder{public static A singleton = new A();}

    public static A getInstance(){return Holder.singleton;}

    April 29, 2011 at 11:50 PM

    Raj said...

    Stored Procedure Error: One way to signal an error is from what is returned.

    Factory/Abstract Factory: Abstract Factory provides one more level of abstraction. Consider different factorieseach extended from an Abstract Factory and responsible for creation of different hierarchies of objects basedon the type of factory. E.g. AbstractFactory extended by AutomobileFactory, UserFactory, RoleFactory etc.Each individual factory would be responsible for creation of objects in that genre.

    June 9, 2011 at 2:29 AM

    Anonymous said...

    I only see 18 questions and most of them are answered wrong or not at all....

    Also, your english is terrible.

    July 24, 2011 at 5:56 PM

    kamal said...

    Question3 Awnser::::::::String s = "Test";

    Will first look for the String "Test" in the string constant pool. If found s will be made to refer to the foundobject. If not found, a new String object is created, added to the pool and s is made to refer to the newly

  • Top 20 Core Java Interview Questions and Answers asked on Investment Banks

    http://javarevisited.blogspot.com/2011/04/top-20-core-java-interview-questions.html[8/3/2014 3:08:01 PM]

    created object.

    String s = new String("Test");

    Will first create a new string object and make s refer to it. Additionally an entry for string "Test" is made inthe string constant pool, if its not already there.

    So assuming string "Test" is not in the pool, the first declaration will create one object while the second willcreate two objects.

    August 3, 2011 at 12:33 AM

    javalearner said...

    @Kamal, I don't think String s = new String("Test");will put the object in String pool , it it does then why do one need String.intern() method which is used to putStrings into String pool explicitly. its only when you create String objec t as String literal e.g. String s = "Test"it put the String in pool.

    August 3, 2011 at 6:52 PM

    Arulkumaran.K said...

    Keep up the good work, and a small suggestion,

    wrap your code snippets in code snippet goes here

    it makes your code snippets more readable.

    September 29, 2011 at 1:04 PM

    Anonymous said...

    Abstract Factory vs Factory(Factory method)AF is used to create a GROUP of logically RELATED objects, AF implemented using FM.Factory just create one of the subclass.As I remember in GoF:AF could create widgets for different types of UI (buttons, windows, labels), but we could have windows, unixetc. UI types, created objects are related by domain.

    October 16, 2011 at 1:57 AM

    Jennifer said...

    If you want to know the top 50 interview questions in banking plus get word-by-word answers to tough bankinginterview questions like Why do you want to do investment banking?, then check out the Free Tutorials at[www] insideinvesmentbanking [dot] com. Its a really useful site and its made by bankers who know theinterview room inside out. PS full disclosure, I am actually a current student of IIB and I do receive help withrecruiting (eg mock interview) in exchange for letting other students know about the Free Tutorials.

    November 10, 2011 at 2:30 PM

    Anonymous said...

    These Java interview question are equally beneficial for 2 years experience or beginners, 4 years experienceJava developers (intermediate) and more than 6 years experience of Java developer i.e. Advanced level. Mostof the questions comes under 2 to 4 years but some of them are good for 6 years experience guy as well likequestions related to executor framework.

    November 15, 2011 at 11:10 PM

    seenu said...

    I agree most of these java interview questions asked during experienced developers and senior developerslevel. though some questions are also good for beginners in Java but most of them are for senior developers injava

    November 24, 2011 at 12:36 AM

    Anonymous said...

    Another popular Java interview question is why Java does not support multiple inheritance, passing reference,or operator overloading, can you please provide answers for those questions. these java interview questionsare little tough to me.

    January 29, 2012 at 6:24 PM

    Anonymous said...

    ..after more than 2.5 year break in my software career, your blog refreshed most of my javaknowledge..thank u so much..i want u to write more n more for beginners n people like me..all the best

  • Top 20 Core Java Interview Questions and Answers asked on Investment Banks

    http://javarevisited.blogspot.com/2011/04/top-20-core-java-interview-questions.html[8/3/2014 3:08:01 PM]

    February 13, 2012 at 9:54 AM

    Anonymous said...

    Hi I am looking for some real tough Java interview question which explores some advanced concept and makesense. if you know real tough, challenging and advanced Java interview questions than please post here.

    April 9, 2012 at 8:50 PM

    Suraj said...

    Hi, I am looking for Java interview questions from Investment banks like Nomura, JPMorgan, Morgan Stanly,Goldman Sachs, UBS, Bank of America or Merrylynch etc. If you have Java questions asked in Nomura or any ofthese banks please share.

    April 22, 2012 at 8:22 PM

    Vineet said...

    Can any one please share core java interview questions from morgan stanley , JP Morgan Chase , Nomura, RBSand Bank of America for experienced professionals of 6 to 7 years experience ? I heard that they mostly askedGarbage Collection, Generics, Design and profiling related questions to senior candidate but some realquestions from those companies will really help.

    June 11, 2012 at 6:31 PM

    Buddhiraj said...

    Hi Javarevisited, looking core java interview questions and answers for experienced in pdf format so that I canuse if offline, Can you please help to convert these Java questions in pdf ?

    June 11, 2012 at 6:43 PM

    Rajat said...

    @Vineet, few Java programming questions asked in google :

    1) Difference between Hashtable and HashMap?2) difference between final, finalize and finaly?3) write LRU cache in Java ?

    let me know if you get more Java questions from google.

    June 18, 2012 at 2:25 AM

    Anand VijayaKumar said...

    Javin

    For question 7 -we usually handle the exception and divert the user to a standard error page with theexception trace as a page variable. The user will have an option to email the support team through a buttonclick and the error trace gets sent to support. This way we can know what went wrong in the application andfix it.

    Typically these kind of errors are due to poor data error handling in stored procedure like a missed null checkor a char variable of incorrect size etc which are exposed only when I consistent data flows into the appwhich was never tested during development or uat.

    Anand

    June 27, 2012 at 6:01 AM

    Javin said...

    @Anand, you bring an important point. size and value of variables are major cause of error in Storedprocedure and if not handle correctly may break Java application. I guess purpose of that java interviewquestion is to check whether you verify inputs in Java or not before passing to Stored procedure and similarlywhen you receive response. Thanks for your comment mate.

    Javin

    June 27, 2012 at 6:27 AM

    Anonymous said...

    1.When we create string with new () its created in heap and not added into string pool while String createdusing literal are created in String pool itself which exists in Perm area of heap.

    2.String s = new String("Test");will put the object in String pool , it it does then why do one need String.intern() method which is used to put

  • Top 20 Core Java Interview Questions and Answers asked on Investment Banks

    http://javarevisited.blogspot.com/2011/04/top-20-core-java-interview-questions.html[8/3/2014 3:08:01 PM]

    Strings into String pool explicitly. its only when you create String object as String literal e.g. String s = "Test"it put the String in pool.

    The above 1 & 2 Stmts are contradicting... when it will in pool and when it will be in heap?

    July 24, 2012 at 5:19 AM

    Bogdan said...

    ...aad here's some more:

    +10voteAnswer #1

    Hey!Ill try to give you some examples, differentiated by the level of the candidate applying:

    **UPDATE**: If you are a junior java developer or an aspiring one, I strongly recommend you to take first theOCJP certification before going to an interview. This can increase your chances to succes big time, as well asyour entry salary proven and tested by myself! :)

    1) Junior java developera) Basic ocjp (former scjp) questions: What does static, final mean, purposes; How many accesibility modifiers exist? Please describe them. Why do you need a main method? How many constructors can you have? Define overwriting and overloading Give java API implementations for overwriting and overloading Describe the String class unique properties StringBuilder vs StringBuffer Collections : please describe, give some examples and compare them to eachother ArrayList vs Vector HashMap vs HashTable Whats a tree Whats a map Multithreading: describe the management in java Whats a semaphone? How many states are there for threads? Describe the usage for synchronized word (2) Serialization in java a descrition and usage Garbage collection in java description and usage Can you guarantee the garbage collection process?b) Simple design pattern questions: Singleton please describe main features and coding Factory please describe main features and coding Have you used others? please describe them

    2) Intermediate and Senior level depending on rate of good responses, additional questions to 1):

    http://centraladvisor.com/programming-2/java/java-developer-interview

    August 1, 2012 at 7:25 AM

    Bhanu P. said...

    Thanks dude, most of your Java interview question is asked on Interview on Sapient, Capagemini, MorganStanley and Nomura.I was giving interview on HSBC last weekend and they ask me How SubString works in Java:). Infosys, TCS, CTS, Barclays Java interview questions at-least one from your blog. We were giving client sideinterview for UBS hongkong and they ask How HashMap works in Java, I don't have word to thank you. Pleasekeep us posting some more tough Java interview question from 2011 and 2012 , which is recent.

    August 31, 2012 at 3:20 AM

    Prabha kumari said...

    Can anyone please share Java interview Question asked on Tech Mahindra, Patni, LnT Infotech and MahindraSatyam. Urgently required, interview scheduled in two days.

    August 31, 2012 at 3:22 AM

    Karan said...

    Some Java programmer ask for Java questions for 2 years experience, Java questions for 4 years experience,questions for Beginners in Java, questions for experienced Java programmer etc etc. Basically all these are

  • Top 20 Core Java Interview Questions and Answers asked on Investment Banks

    http://javarevisited.blogspot.com/2011/04/top-20-core-java-interview-questions.html[8/3/2014 3:08:01 PM]

    just short cut, you should be good on what are you doing. You automatically gain experience while working inJava and should be able to answer any Java question up-to your level.

    September 2, 2012 at 11:43 PM

    Putti said...

    Hi Guys, Can some one share Java interview questions from Directi, Thoughtworks, Wipro, TCS and Capegeminifor experienced Java programmer 6+ years experience ?

    September 18, 2012 at 8:46 PM

    Sonam said...

    Hi , Does Amazon or Microsoft ask questions on Java ? I am looking for some Java questions asked onMicrosoft, Amazon and other technology companies, if you know please share.

    September 25, 2012 at 11:57 PM

    Arulkumaran Kumaraswamipillai said...

    You have no control over what questions get asked in job interviews. All you can do is brush up on the keyfundamentals.

    October 17, 2012 at 6:50 PM

    Anonymous said...

    your questions are good but answers are not satisfactory. we know better than your answer. try to give somenew answer so that someone will read with a interest.

    January 6, 2013 at 8:01 PM

    Ravi said...

    Hi Javin,

    I'd like to thank you for putting huge effort in creating such nice collection.

    Kindly update following in your blog:Regarding Question-3. you wrote:

    String s = new String("Test"); does not put the object in String pool

    This is not correct. using new will create two objects one in normal heap and another in Pool and s will pointto object in heap.

    It will be nice for others if you can update this in your blog.

    January 28, 2013 at 12:16 AM

    Javin @ ClassLoader in Java said...

    Hi Ravi, where did you read that? I have never heard about String object created on both heap and pool.Object is placed into pool when you call intern method on String object.

    January 28, 2013 at 4:09 AM

    Anonymous said...

    Can you please suggest some latest Java interview questions from 2012, 2011 and what is trending now days.Questions like Iterator vs Enumeration is way older and I think latest question on Java is more on Concurrency.

    January 28, 2013 at 10:47 PM

    garima said...

    Hi Javin,String s = new String("Test"); // creates two objects and one reference variableIn this case, because we used the new keyword, Java will create a new String objectin normal (nonpool) memory, and s will refer to it. In addition, the literal "Test" willbe placed in the pool.

    January 30, 2013 at 7:19 AM

    Anonymous said...

    Although, questions are good, you can add lot more interview questions form Java 5, 6 and Java 7. Even lamdaexpression from Java 8 can be a nice question. I remember, having interview with Amazon, Google andMicrosoft, there were hardly any Java question, but when I interviewed by Nomura, HeadStrong, and Citibank,there are lots of questions from Java, Generics, Enum etc. Lesson learned, always research about what kind ofquestion asked in a company, before going to interview.

  • Top 20 Core Java Interview Questions and Answers asked on Investment Banks

    http://javarevisited.blogspot.com/2011/04/top-20-core-java-interview-questions.html[8/3/2014 3:08:01 PM]

    March 12, 2013 at 11:04 PM

    Dheeraj said...

    Can you please post latest Java Interview Questions from Investment banks like Citibank, Credit Suisse,Barclays, ANZ, Goldman Sachs, Morgan Stanly, CLSA, JP Morgan and some high frequency hedge funds likeMillenium? I am preparing for Java interview, and looking for recent questions asked in 2012, 2013 or may bein last couple of month. If you can get question from Singapore, HongKong or London, that would be reallyhelpful, but I don't mind question form Pune, Bangalore or Mumbai even.

    CheersDheeraj

    March 28, 2013 at 2:46 AM

    Thorsten Hoeger said...

    Hi, for number 19 it might be better to use System.nanoTime() as currentTimeMillis may have problems withsmall intervals.

    March 30, 2013 at 2:31 AM

    Peter said...

    Surprised to See no questions from Java IO or NIO. I think, Investment banks used lot of non blocking I/O codefor socket programming, connecting system with TCP/IP. In Exchange Connectivity code, I have seen lot of useByteBuffer for reading positional protocol. I think, you should also include questions from Garbage Collectiontuning, Java concurrency package, very hot at the moment.

    March 31, 2013 at 9:01 PM

    jv said...

    q3. What is the difference between creating String as new() and literal?ans is not correct bcz String x=new String("abc")-creates two object.one is in heap memory and second is in constant string pool.

    April 2, 2013 at 8:23 PM

    Deepak said...

    Hello, Can some one please share interview questions from ANZ Banglore and Singapore location, I need iturgently.

    April 9, 2013 at 9:30 PM

    Anonymous said...

    There is lot more difference in Java Interviews in India and other countries like USA (NewYork), UK(London),Singapore, Hongkong or any other europian counties. India is mostly about theoretical knowledge e.gdifference between StringBuffer and StirngBuilder, final, finalize or finally , bla bla bla............

    USA in particular is more about Code, they will give you a problem and ask you to code solution , write unittest, produce design document in limited time usually 3 to 4 hours. One of the example is coding solution forVending Machine, CoffeMaker, ATM Machine, PortfolioManager, etc .

    Trends on other countries are also more balanced towards code e.g. writing code to prevent deadlock (that's atricky one), So be prepare accordingly.

    RAJAT

    April 11, 2013 at 9:02 PM

    Anonymous said...

    Hi Javin, Can you please share some Core Java questions from Java 6 and Java 7? I heard they are asking newfeatures introduced in Java 6 as well as Java 7. Please help

    April 19, 2013 at 1:07 AM

    Anonymous said...

    How HashMap works, this question was asked to me on Barclays Capital Java Interview question, would haeread this article before, surely helped me.

    April 22, 2013 at 12:04 AM

    Gourav Yadav said...

    @Ravi,Garima,Javin

    its regarding String creation in Pool

  • Top 20 Core Java Interview Questions and Answers asked on Investment Banks

    http://javarevisited.blogspot.com/2011/04/top-20-core-java-interview-questions.html[8/3/2014 3:08:01 PM]

    I tested a small code and giving results like below:

    String s="Test";String s1=new String("Test");

    System.out.println(s==s1);//return falseSystem.out.print(s==s1.intern()); //retun true

    If we go by concept that string creation adds string to pool also then first result should be true as if alreadysame string(mean s) is present in pool then same object is returned back so s1 should point to s but the resultis coming as false.

    On the contrary,when we invoke intern method on s1 and then compare it returns true as it adds string topool which is normal working of intern method.

    Please correct me if I am wrong.

    April 22, 2013 at 1:19 AM

    Anonymous said...

    hi Javin, Can you please share some Citibank Java Interview questions? I have an interview with CitibankSingapore for Algorithmic trading developer position, and expecting few Java questions? Would be great if youcould share some questions from Citibank, Credit Suisse, UBS or ANZ, these are my target companies. Cheers

    April 29, 2013 at 11:41 PM

    Gautam said...

    @Anonymous, are you asking for Citigroup Java developer position or Citibank?

    May 1, 2013 at 7:18 PM

    supriya marathe said...

    one question commonly asked is why JVM or why is jvm platform independent

    May 24, 2013 at 6:28 AM

    Anonymous said...

    @supriya, JVM is platform dependent, only bytecode is platform independent.

    May 29, 2013 at 5:30 AM

    Nikhil said...

    Nikhil: Question 19 To find out time taken by method to execute System.currentTimeInMillis() will not be accurate as it will also include time for which current thread waiteddue to context switch. Below approach should be used:

    ThreadMXBean threadMX = ManagementFactory.getThreadMXBean();

    long start = threadMX.getCurrentThreadUserTime();// time-consuming operation herelong finish = threadMX.getCurrentThreadUserTime();

    http://nadeausoftware.com/articles/2008/03/java_tip_how_get_cpu_and_user_time_benchmarking

    June 1, 2013 at 8:55 AM

    Ravi said...

    @Javin,

    I read it in SCJP for Java 6 book by Kathy Sierra page 434. I am copying and pasting same here..

    ----------------------String s = "abc";

    // creates one String object and one reference variable. In this simple case, "abc" will go in the pool and swill refer to it.

    String s = new String("abc");

    // creates two objects, and one reference variable. In this case, because we used the new keyword, Java willcreate a new String objectin normal (nonpool) memory, and s will refer to it. In addition, the literal "abc" willbe placed in the pool.

  • Top 20 Core Java Interview Questions and Answers asked on Investment Banks

    http://javarevisited.blogspot.com/2011/04/top-20-core-java-interview-questions.html[8/3/2014 3:08:01 PM]

    ----------------------

    June 9, 2013 at 3:24 AM

    Xhotery said...

    These questions are quite basic and only useful for freshers or beginners Java developers. I wouldn't say, youcan expect this question as Senior Java developer. Everyone knows answers, there is nothing special about it.definitely not TOP questions in my opinion.

    August 14, 2013 at 7:33 PM

    Anonymous said...

    I agree with Xhotery, this questions are from 2012 and 2011 years, now it's 2013. In order to crack Javainterview today, you need to focus extensively on JVM internals, deeper knowledge of Java Concurrency,sophisticated open source library and good knowledge of frameworks like Spring, Hibernate, Maven, and evenbit of functional programming knowledge is required. In recent Java interviews, peoples are asking aboutlambdas of Java 8 and How it's going to improve performance, questions about functional interface and newdate and time library. Even questions from Java 7 e.g. try with resource and String in Switch are quite popularnowadays. So be more advanced and prepare relevant questions, which is popular in 2013, not two years back.

    August 26, 2013 at 7:41 PM

    Anonymous said...

    Some of the Interview questions for senior developers :

    1. Difference between Abstract & Interface - given a situation what would you choose between abstration &interface2) Difference between inheritance & composition3. Difference between Arraylist and linked list4. difference between sleep and wait5. Explain about hashmap ( methods in hashmap & the project in which we have used the hashmap moreabout equalsto and hashcode) 6. Explain about the methods in Object7. What is coupling8. Struts config file - can there be multiple configs9. Design patterns - factory , abstract factory, singleton implemented?

    August 27, 2013 at 4:31 AM

    Anonymous said...

    These questions and answers are ok, but they look more suited for junior developers than senior engineers tome.

    Just few quick remarks from me:

    1. Immutability in Java is not that easy to achieve, as long as we have reflexion. Of course, in theory,reflexion can be disabled from a security provider. But in practice, a Java application uses severaltechnologies that rely on reflexion (anything that does dependency injection (Spring, EJB containers etc.),anything that uses "convention over configuration" (ex: expression language etc.)), so in practice it's notpossible to disable reflexion most of the times.

    10. In Java a java-core environment, singleton means single instance per class loader (not per application!). Inother contexts it may mean single instance per container, etc.

    19. Your answer here is absolutely wrong. On one hand, if you just invoke that method for the very first time,you'll not find the net amount of time taken by method execution, but the gross amount of time includingmethod execution plus class loading time for all classes that are referred for the first time inside that method.Second thing, by measuring that way, you completely ignore how java works: all the adaptive optimization theJIT does at runtime dramatically changes the execution time after a number of method calls. Actually, thefirst call of a method is the wrongest way to measure its execution time.

    September 16, 2013 at 1:57 AM

    jitu said...

    Hi Javin,

    I'd like to thank you for putting huge effort in creating such nice collection.

    Kindly update following in your blog:Regarding Question-3. you wrote:

    String s = new String("Test"); does not put the object in String pool

    This is not correct. using new will create two objects one in normal heap and another in Pool and s will point

  • Top 20 Core Java Interview Questions and Answers asked on Investment Banks

    http://javarevisited.blogspot.com/2011/04/top-20-core-java-interview-questions.html[8/3/2014 3:08:01 PM]

    to object in heap.

    Reference : Effective Java second edition item 5 or 6It will be nice for others if you can update this in your blog.

    October 20, 2013 at 9:47 AM

    Anand Vijay Kumar said...

    Given it's 2013, Java Interviews has changed a lot with more focus on JVM internals, Garbage Collection tuningand performance improvement. Here is a list of questions, which I have faced recently in Java interviews :

    1) What is Composite design pattern?2) Explain Liskov substitution principle ?3) Write a Java program to convert bytes to long?4) What is false sharing in multithreading Java?5) Can we make an array volatile in Java? What is effect of making it volatile?6) What is advantage and disadvantage of busy spin waiting strategy?7) Difference between DOM and SAX parser in Java?8) Write wait notify code for producer consumer problem?9) Write code for thread-safe Singleton in Java?10) What are 4 ways to iterate over Map in Java? Which one is best and why?11) Write code to remove elements from ArrayList while iterating?12) is Swing thread-safe?13) What is thread local variable in Java?14) How do you convert an String to date in Java?15) Can we use String in switch case?16) What is constructor chaining in Java?17) Explain Java Heap space and Garbage collection?18) Difference between major and minor GC?19) Difference between -Xmx and -Xms JVM option?20) How to check if a String contains only numeric digits?21) Difference between poll() and remove() method of Queue in Java?22) Difference between Comparator and Comparable in Java?23) Why you need to override hashcode, when you override equals in Java?24) How HashSet works internally in Java?25) How do you print Array in Java?

    All the best for your Java Interviews.

    December 25, 2013 at 8:13 PM

    Anonymous said...

    Some exercises for an interview that I had with Morgan Stanley(in 2014):

    1. Explain what 'path to root' means in the context of garbage collection. What are roots?2. Write code for a simple implementation of HashMap/Hashtable3. Write a short program to illustrate the concept of deadlock4. Explain why recursive implementation of QuickSort will require O(log n) of additional space5. Explain the design pattern used in Java and .NET io stream/reader APIs.6. Create an Iterator filtering framework: an IObjectTest interface with a single boolean test(Object o) methodand an Iterator sub-class which is initialized with another Iterator and an IObjectTest instance. Your iteratorwill then allow iteration over the original, but skipping any objects which don't pass the test. Create a simpleunit test for this framework.

    January 15, 2014 at 7:15 PM

    Surendar said...

    Hi,

    The Answer to 3. question is wrong. When creating string using new will create two copies one in heap andanother in string pool. And the object reference will be initially in heap. Inorder to make the object referenceto string pool we need to call intern() on the string.

    February 19, 2014 at 2:00 AM

    cbp said...

    This comment has been removed by the author.

    March 22, 2014 at 7:17 AM

    cbp said...

    First of all, thank you so much for putting this page together. It is a great starting point to refresh someconcepts before going into an interview. I would also recommend that everyone study the book 'Effective Java'

  • Top 20 Core Java Interview Questions and Answers asked on Investment Banks

    http://javarevisited.blogspot.com/2011/04/top-20-core-java-interview-questions.html[8/3/2014 3:08:01 PM]

    too. I wanted to bring up a point that JCIP discusses in Chapter 16.

    "Double checked locking is an anti-pattern..." -Java Concurrency in Practice p. 213

    Yes, since Java 5 we can use the volatile keyword for the instance variable and this fixes a rather fatal flaw(explained below), but the need to use this ugly anit-pattern doesn't exist when you can just synchronize thegetInstance() method.

    //ALL YOU NEEDpublic static synchronized getInstance() {if (INSTANCE == null) {//create instance}return INSTANCE;}

    "The real problem with DCL is the assumption that the worst thing that can happen when reading a sharedobject reference without synchronization is to erroneously see a stale value (in this case, null); in that casethe DCL idiom compensates for this risk by trying again with the lock held. But the worst case is actuallyconsiderably worse - it is possible to see a current value of the reference but stale values for the object'sstate, meaning that the object could be seen to be in an invalid or incorrect state." -Java Threads In Practicep. 214

    March 22, 2014 at 8:19 AM

    Anonymous said...

    Method submit extends base method Executor.execute(java.lang.Runnable) by creating and returning a Futurethat can be used to cancel execution and/or wait for completion. Methods invokeAny and invokeAll performthe most commonly useful forms of bulk execution, executing a collection of tasks and then waiting for atleast one, or all, to complete. (Class ExecutorCompletionService can be used to write customized variants ofthese methods.)

    March 28, 2014 at 12:34 PM

    Anonymous said...

    Hi alli have an interview in RAK bank for the post java developer..if anyone know about the interview questionsplease help

    May 21, 2014 at 3:42 AM

    Post a Comment

    blogspot.comTop 20 Core Java Interview Questions and Answers asked on Investment Banks