Core Java Interview Question Answer
This is a new series of sharing core Java interview question and answer on Finance domain and mostly on big Investment bank.Many of these Java interview questions are asked on JP Morgan, Morgan Stanley, Barclays or 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 Interview on any Investment bank can be benefited from these set of core Java Interview questions and answers. I have collected these Java questions from my friends and I thought to share with you all. I hope this will be helpful for both of us. It's also beneficial to practice some programming interview questions because in almost all Java interview, there is at-least 1 or 2 coding questions appear. Please share answers for unanswered Java interview questions 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 is not supported in Java is one of the tricky question in java. Most questions are asked on Senior and experienced level i.e. 3, 4, 5 or 6 years of Java experience e.g. How HashMap works in Java, which is most popular on experienced Java interviews. By the way recently I was looking at answers and comments made on Java interview questions given in this post and I found some of them quite useful to include into main post to benefit all.
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 not be modified once created. Any modification in Immutable object result in new object. For example is String is immutable in Java. Mostly Immutable are also final in Java, in order to prevent sub class from overriding methods in Java which can compromise Immutability. You can achieve same functionality by making member as non final but private and not modifying them except in constructor.
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 private and not modifying them except in constructor.
3. What is the difference between creating String as new() and literal?
When we create string with new() Operator, it’s created in heap and not added into string pool while String created using literal are created in String pool itself which exists in PermGen area of heap.
does not put the object in String pool , we need to call String.intern() method which is used to put 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.
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 object out of source string by taking a portion of original string”. see my post How SubString works in Java for detailed answer of this Java question.
5. Which two method you need to implement for key Object in HashMap ?
In order to use any object as Key in HashMap, it must implements equals and hashcode method in Java. Read How HashMap works in Java for detailed explanation on how equals and hashcode method is used to put and get object from HashMap. You can also see my post 5 tips to correctly override equals in Java to learn more about equals.
6. Where does these two method comes in picture during get operation?
This core Java interview question is follow-up of previous Java question and candidate should know that once you mention hashCode, people are most likely ask How its used in HashMap. See How HashMap works in Java for detailed explanation.
7. How do you handle error condition while writing stored procedure or accessing stored procedure from java?
This is one of the tough Java interview question and its open for all, my friend didn't know the answer so he didn't mind telling me. my take is that stored procedure should return error code if some operation fails but if stored 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 popular day by day because of huge demand of Java developer with good concurrency skill. Answer of this Java interview question is that former returns an object of Future which can be used to find result from worker thread)
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 was submitted with execute this exception will go to the uncaught exception handler (when you don't have provided one explicitly, the default one will just print the stack trace to System.err). If you submitted the task 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 of you to answer.
@Raj suggestedAbstract Factory provides one more level of abstraction. Consider different factories each extended from an Abstract Factory and responsible for creation of different hierarchies of objects based on 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.
You can also refer What is Factory method design pattern in Java to know more details.
10. What is Singleton? is it better to make whole method synchronized or only critical section synchronized ?
Singleton in Java is a class with just one instance in whole Java application, for example java.lang.Runtime is 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 and double 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 using double checked locking. Remember to use volatile variable to make Singleton thread-safe. check 10 Interview questions 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.
13. When do you override hashcode and equals() ?
Whenever necessary especially if you want to do equality check or want to use your object as key in HashMap. check this for writing equals method correctly 5 tips on equals in Java
14. What will be the problem if you don't override hashcode() method ?
You will not be able to recover your object from hash Map if that is used as key in HashMap.
See here How HashMap works in Java for detailed explanation.
15. Is it better to synchronize critical section of getInstance() method or whole getInstance() method ?
Answer is critical section because if we lock whole method than every time some one call this method will have to wait even though we are not creating any object)
16. What is the difference when String is gets created using literal or new() operator ?
When we create string with new() its created in heap and not added into string pool while String created using literal are created in String pool itself which exists in Perm area of heap.
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 frequent collision in HashMap which eventually increase time for adding an object into Hash Map.
18. What’s wrong using HashMap in multithreaded environment? When get() method go to infinite loop ?
Another good question. His answer was during concurrent access and re-sizing.
19. Give a simplest way to find out the time a method takes for execution without using any profiling tool?
this questions is suggested by @Mohit
Read the system time just before the method is invoked and immediately after method returns. Take the time difference, 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 for execution. Try it on a method which is big enough, in the sense the one which is doing considerable amout of processing


68 comments:
all answers related to singletons in Java seem to ignore the "double-checked locking is broken" problem; it is best to initialize the single instance in the class initializer.
private final SingletonClass INSTANCE = new SingletonClass();
Thanks Job good to know that these java interview questions are useful for you.
Thanks a lot Anonymous for informing us about subtle details about Substring() method , I guess Interviewer was looking for that information in his question "How does substring () inside String works?" because if substring also shares same byte array then its something to be aware of.
Hi Scott,
your solution is correct but with the advent of java 5 and now guarantee of volatile keyword and change in Java memory model guarantees that double checking of singleton will work. another solution is to use Enum Singeton. you can check my post about Singleton here Singleton Pattern in Java
Hi Anand,
Thanks for answering question "How does substring () inside String works?"
Great compilation Javin. Keep sharing your knowledge with us.
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;
}
Hi emt, Thanks for your suggestion and code example , this is definitely one of way to creating Singleton.
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 factories each extended from an Abstract Factory and responsible for creation of different hierarchies of objects based on 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.
I only see 18 questions and most of them are answered wrong or not at all....
Also, your english is terrible.
Not satiesfied,, not given proper answers
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 found object. If not found, a new String object is created, added to the pool and s is made to refer to the newly 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 in the 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 will create two objects.
@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 put Strings 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.
Nice interview question materials. Following are the links where some java interview question and answers are available.
http://jksnu.blogspot.com/2011/07/collection-of-my-posts.html
http://jksnu.blogspot.com/2011/09/interview-questions-core-java-volume-2.html
http://jksnu.blogspot.com/2011/09/interview-questions-jdbc-volume-1.html
http://jksnu.blogspot.com/2011/09/interview-questions-jdbc-volume-2.html
http://jksnu.blogspot.com/2011/09/interview-questions-jdbc-volume-3.html
Keep up the good work, and a small suggestion,
wrap your code snippets in <pre class="brush: csharp"> code snippet goes here </pre>
it makes your code snippets more readable.
Thanks Arul, I will definitely give it a try.
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, unix etc. UI types, created objects are related by domain.
"all its member final" should be
"all it's members final"
If you want to know the top 50 interview questions in banking plus get word-by-word answers to tough banking interview questions like “Why do you want to do investment banking?”, then check out the Free Tutorials at [www] insideinvesmentbanking [dot] com. It’s a really useful site and it’s made by bankers who know the interview room inside out. PS full disclosure, I am actually a current student of IIB and I do receive help with recruiting (eg mock interview) in exchange for letting other students know about the Free Tutorials.
These Java interview question are equally beneficial for 2 years experience or beginners, 4 years experience Java developers (intermediate) and more than 6 years experience of Java developer i.e. Advanced level. Most of the questions comes under 2 to 4 years but some of them are good for 6 years experience guy as well like questions related to executor framework.
I agree most of these java interview questions asked during experienced developers and senior developers level. though some questions are also good for beginners in Java but most of them are for senior developers in java
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 questions are little tough to me.
Great workl
nice Most Most Important 40 J2EE Interview Questions with Answers http://www.javastuff.in/2012/02/most-important-40-j2ee-interview.html
..after more than 2.5 year break in my software career, your blog refreshed most of my java knowledge..thank u so much..i want u to write more n more for beginners n people like me..all the best
Good Stuff. Here is some Important Questions
http://www.javastuff.in/2012/02/top-java-interview-questions.html
Hi I am looking for some real tough Java interview question which explores some advanced concept and make sense. if you know real tough, challenging and advanced Java interview questions than please post here.
http://zaakuu-javacrack.blogspot.com/ - Looks like a good overall Java/J2EE Starter
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 of these banks please share.
Great tutorials guys, thank you! But gush...you guys really need to work on your written English and grammar...
veryy.......nice
i think these questions will very helpful to ours
Good efforts! Always asked in interview, what I am not satisfied these answers mostly question because these are not best for interview purpose.........
Can any one please share core java interview questions from morgan stanley , JP Morgan Chase , Nomura, RBS and Bank of America for experienced professionals of 6 to 7 years experience ? I heard that they mostly asked Garbage Collection, Generics, Design and profiling related questions to senior candidate but some real questions from those companies will really help.
Hi Javarevisited, looking core java interview questions and answers for experienced in pdf format so that I can use if offline, Can you please help to convert these Java questions in pdf ?
@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.
Javin
For question 7 -we usually handle the exception and divert the user to a standard error page with the exception trace as a page variable. The user will have an option to email the support team through a button click and the error trace gets sent to support. This way we can know what went wrong in the application and fix it.
Typically these kind of errors are due to poor data error handling in stored procedure like a missed null check or a char variable of incorrect size etc which are exposed only when I consistent data flows into the app which was never tested during development or uat.
Anand
@Anand, you bring an important point. size and value of variables are major cause of error in Stored procedure and if not handle correctly may break Java application. I guess purpose of that java interview question is to check whether you verify inputs in Java or not before passing to Stored procedure and similarly when you receive response. Thanks for your comment mate.
Javin
1.When we create string with new () it’s created in heap and not added into string pool while String created using 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 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?
...aad here's some more:
+1
0
vote
Answer #1
Hey!
I’ll 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 the OCJP certification before going to an interview. This can increase your chances to succes big time, as well as your entry salary – proven and tested by myself! :)
1) Junior java developer
a) 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
– What’s a tree
– What’s a map
– Multithreading: describe the management in java
– What’s 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
Thanks dude, most of your Java interview question is asked on Interview on Sapient, Capagemini, Morgan Stanley 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 side interview for UBS hongkong and they ask How HashMap works in Java, I don't have word to thank you. Please keep us posting some more tough Java interview question from 2011 and 2012 , which is recent.
Can anyone please share Java interview Question asked on Tech Mahindra, Patni, LnT Infotech and Mahindra Satyam. Urgently required, interview scheduled in two days.
Hi javin, Good collection of interview questions..keep it up.
for more real time interview questions on java in a pdf file you can download here.Java interview Questions to Download
Good question, here is another list of tough and tricky Java question answer.
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 just short cut, you should be good on what are you doing. You automatically gain experience while working in Java and should be able to answer any Java question up-to your level.
Fantastic questions and answers are quite good. here is another list of tricky interview questions in Java
Hi Guys, Can some one share Java interview questions from Directi, Thoughtworks, Wipro, TCS and Capegemini for experienced Java programmer 6+ years experience ?
Hi , Does Amazon or Microsoft ask questions on Java ? I am looking for some Java questions asked on Microsoft, Amazon and other technology companies, if you know please share.
You have no control over what questions get asked in job interviews. All you can do is brush up on the key fundamentals.
your questions are good but answers are not satisfactory. we know better than your answer. try to give some new answer so that someone will read with a interest.
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 to object in heap.
It will be nice for others if you can update this in your blog.
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.
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.
Hi Javin,
String s = new String("Test"); // creates two objects and one reference variable
In this case, because we used the new keyword, Java will create a new String object
in normal (nonpool) memory, and s will refer to it. In addition, the literal "Test" will
be placed in the pool.
Although, questions are good, you can add lot more interview questions form Java 5, 6 and Java 7. Even lamda expression from Java 8 can be a nice question. I remember, having interview with Amazon, Google and Microsoft, 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 of question asked in a company, before going to interview.
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 like Millenium? I am preparing for Java interview, and looking for recent questions asked in 2012, 2013 or may be in last couple of month. If you can get question from Singapore, HongKong or London, that would be really helpful, but I don't mind question form Pune, Bangalore or Mumbai even.
Cheers
Dheeraj
Hi, for number 19 it might be better to use System.nanoTime() as currentTimeMillis may have problems with small intervals.
Surprised to See no questions from Java IO or NIO. I think, Investment banks used lot of non blocking I/O code for socket programming, connecting system with TCP/IP. In Exchange Connectivity code, I have seen lot of use ByteBuffer for reading positional protocol. I think, you should also include questions from Garbage Collection tuning, Java concurrency package, very hot at the moment.
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.
Hello, Can some one please share interview questions from ANZ Banglore and Singapore location, I need it urgently.
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.g difference 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 unit test, produce design document in limited time usually 3 to 4 hours. One of the example is coding solution for Vending 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 a tricky one), So be prepare accordingly.
RAJAT
Hi Javin, Can you please share some Core Java questions from Java 6 and Java 7? I heard they are asking new features introduced in Java 6 as well as Java 7. Please help
How HashMap works, this question was asked to me on Barclays Capital Java Interview question, would hae read this article before, surely helped me.
@Ravi,Garima,Javin
its regarding String creation in Pool
I tested a small code and giving results like below:
String s="Test";
String s1=new String("Test");
System.out.println(s==s1);//return false
System.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 already same string(mean s) is present in pool then same object is returned back so s1 should point to s but the result is coming as false.
On the contrary,when we invoke intern method on s1 and then compare it returns true as it adds string to pool which is normal working of intern method.
Please correct me if I am wrong.
Very good collection of java concepts....thanks
hi Javin, Can you please share some Citibank Java Interview questions? I have an interview with Citibank Singapore for Algorithmic trading developer position, and expecting few Java questions? Would be great if you could share some questions from Citibank, Credit Suisse, UBS or ANZ, these are my target companies. Cheers
@Anonymous, are you asking for Citigroup Java developer position or Citibank?
one question commonly asked is why JVM or why is jvm platform independent
Post a Comment