Thursday, August 12, 2021

Top 20 Core Java Interview Questions and Answers from Investment Banks

Core Java Interview Question Answer
This is a new series of sharing core Java interview questions and answer on the Finance domain and mostly on big Investment banks. 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 this set of core Java Interview questions and answers. I have collected these Java questions from my friends and I thought to share them 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 interviews, there are 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? 

If you are seriously preparing for Java Interviews and attending interviews, then I also suggest taking a look at these Java interview online courses and books. This is the Java-specific book modeled on their earlier bestseller, also about programming interviews. 

This book contains questions not just from Java but also from related technology stacks like JUnit, Maven, Design Patterns, JVM Internals, Android, and Best practices. Questions are good and answers are crisp and very well explained, which makes it an interesting to read as well.



20+ Core Java Interview Questions Answers

These Java interview questions are a mix of easy, tough, and tricky Java questions e.g. Why multiple inheritance is not supported in Java is one of the tricky questions in java. Most questions are asked on Senior and experienced levels 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 in the main post to benefit all.

By the way apart from blogs and articles, you can also take advantage of some books and online courses, which are specially written for clearing any programming interviews and some focused on Java programming, two books that come to mind are Cracking the Coding Interview and Programming Interviews Exposed. 

Both books and courses are focused on programming in general and a lot of other related topics e.g. data structures, algorithms, database, SQL, networking, and behavioral questions, but also contain Java concepts.

Core Java Interview Questions from Investment Banks



Question 1: What’s wrong with using HashMap in the multi-threaded environment? When get() method go to the infinite loop? (answer)
Well, nothing is wrong, it depends upon how you use it. For example, if you initialize the HashMap by just one thread and then all threads are only reading from it, then it's perfectly fine. One example of this is a Map that contains configuration properties. 

The real problem starts when at least one of those threads is updating HashMap i.e. adding, changing, or removing any key-value pair. Since put() operation can cause re-sizing and which can further lead to an infinite loop, that's why either you should use Hashtable or ConcurrentHashMap, later is better.


Question 2. Does not overriding hashCode() method has any performance implication? (answer)
This is a good question and open to all, as per my knowledge, a poor hashcode function will result in the frequent collision in HashMap which eventually increases the time for adding an object into HashMap. 

From Java 8 onwards though collision will not impact performance as much as it does in earlier versions because after a threshold the linked list will be replaced by the binary tree, which will give you O(logN) performance in the worst case as compared to O(n) of linked list. 



Question 3: Does all property of Immutable Object needs to be final? (answer)
Not necessary, as stated above you can achieve the same functionality by making members non-final but private and not modifying them except in the constructor. Don't provide a 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 ensures that it will not be reassigned a different value, but you can still change individual properties of an object, pointed by that reference variable. This is one of the key points, Interviewer likes to hear from candidates. 



Question 4: How does substring () inside String works? (answer)
Another good Java interview question, I think the answer is not sufficient, but here it is “Substring creates a new object out of source string by taking a portion of original string”. This question was mainly asked to see if the developer is familiar with the risk of memory leak, which sub-string can create. 

Until Java 1.7, substring holds the reference of the original character array, which means even a sub-string of 5 characters long, can prevent 1GB character array from garbage collection, by holding a strong reference.


Java interview questions for freshers

This issue is fixed in Java 1.7, where the original character array is not referenced anymore, but that change also made the creation of substring a bit costly in terms of time. Earlier it was in the range of O(1), which could be O(n) in the worst case on Java 7.


Question 5: Can you write critical section code for the singleton? (answer)
This core Java question is a follow-up of the previous question and expecting the candidate to write Java singleton using double-checked locking. Remember to use the volatile variable to make Singleton thread-safe. Here is the code for critical section of a thread-safe Singleton pattern using double checked locking idiom:
public class Singleton {

    private static volatile Singleton _instance;

    /**
     * Double checked locking code on Singleton
     * @return Singelton instance
     */
    public static Singleton getInstance() {
        if (_instance == null) {
            synchronized (Singleton.class) {
                if (_instance == null) {
                    _instance = new Singleton();
                }
            }
        }
        return _instance;
    }

}


Question 6: How do you handle error conditions while writing stored procedures or accessing stored procedures from java? (answer)
This is one of the tough Java interview questions and it's 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 an error code if some operation fails but if the stored procedure itself fails then catching SQLException is the only choice.




Question 7 : What is difference between Executor.submit() and Executer.execute() method ? (answer)
This Java interview question is from my list of Top 15 Java multi-threading question answers, It's getting popular day by day because of the huge demand for Java developers with good concurrency skills. The answer to this Java interview question is that former returns an object of Future which can be used to find results from worker thread)

There is a difference when looking at exception handling. If your tasks throw an exception and if it was submitted with executing 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 submitting and that terminates with an exception, the Future.get() will re-throw this exception, wrapped in an ExecutionException.



Question 8:  What is the difference between a factory and abstract factory patterns? (answer)
Abstract Factory provides one more level of abstraction. Consider different factories each extended from an Abstract Factory and responsible for the 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 the creation of objects in that genre. 

Here is a UML diagram of factory and abstract factory pattern:

Java interview questions for experienced




Question 9: What is Singleton? is it better to make the whole method synchronized or only critical section synchronized? (answer)
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 the enum and double checked locking which is the purpose of this Java interview question.


Question 10:  Can you write code for iterating over HashMap in Java 4 and Java 5? (answer)
Tricky one but he managed to write using while and a for loop. Actually, there are four ways to iterate over any Map in Java, one involves using keySet() and iterating over key and then using get() method to retrieve values, which is bit expensive. 

The second method involves using entrySet() and iterating over them either by using for each loop or while with Iterator.hasNext() method. This one is a better approach because both key and value object are available to you during Iteration and you don't need to call get() method for retrieving the value, which could give the O(n) performance in case of huge linked list at one bucket. See my post 4 ways to iterate over Map in Java for detailed explanation and code examples.

20+ Java Interview Questions and Answers


Question 11 : When do you override hashCode() and equals()? (answer)
Whenever necessary especially if you want to do an equality check based upon business logic rather than object equality e.g. two employee objects are equal if they have the same emp_id, despite the fact that they are two different objects, created by a different parts of the code. Also overriding both these methods are a must if you want to use them as key in HashMap. 


Now as part of the equals-hashcode contract in Java, when you override equals, you must override hashcode as well, otherwise, your object will not break invariant of classes e.g. Set, Map which relies on equals() method for functioning properly. You can also check my post 5 tips on equals in Java to understand subtle issue which can arise while dealing with these two methods.


Question 12:. What will be the problem if you don't override hashCode() method? (answer)
If you don't override the equals method, then the contract between equals and hashcode will not work, according to which, two objects which are equal to equals() must have the same hashcode. In this case, another object may return different hashCode and will be stored in that location, which breaks the invariant of the HashMap class because they are not supposed to allow duplicate keys. 

When you add the object using the put() method, it iterates through all Map.Entry object present in that bucket location, and update value of the previous mapping, if Map already contains that key. This will not work if the hashcode is not overridden.


Java interview questions with answer



Question 13 : Is it better to synchronize critical section of getInstance() method or whole getInstance() method? (answer)
The answer is only a critical section because if we lock the whole method that every time someone calls this method, it will have to wait even though we are not creating any object. In other words, synchronization is only needed, when you create an object, which happens only once. 

Once an object has been created, there is no need for any synchronization. In fact, that's very poor coding in terms of performance, as the synchronized methods reduce performance up to 10 to 20 times. 

Here is a UML diagram of the Singleton pattern:
By the way, there are several ways to create a thread-safe singleton in Java, which you can also mention as part of this question or any follow-up.


Question 14: Where does equals() and hashCode() method comes in the picture during the get() operation? (answer)
This core Java interview question is a follow-up of a previous Java question and the candidate should know that once you mention hashCode, people are most likely ask, how they are used in HashMap.

When you provide a key object, first its hashcode method is called to calculate bucket location. Since a bucket may contain more than one entry as a linked list, each of those Map.Entry object is evaluated by using equals() method to see if they contain the actual key object or not. 


Questions 15: How do you avoid deadlock in Java? (answer)
You can avoid deadlock by breaking circular wait conditions. In order to do that, you can make arrangements in the code to impose the ordering on the acquisition and release of locks. If the lock will be acquired in a consistent order and released in just the opposite order, there would not be a situation where one thread is holding a lock that is acquired by another and vice-versa. See the detailed answer for the code example and a more detailed explanation.


Question 16:  What is the difference between creating String as new() and literal? (answer)
When we create the string with a 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 the PermGen area of heap.
String str = new String("Test")

does not put the object str in the String pool, we need to call 
String.intern() method which is used to put them into the String pool explicitly. It's 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 arguments as "Test", which is a string literal, it will also create another object as "Test" on the string pool. This is the one point, which has gone unnoticed until knowledgeable readers of the Javarevisited blog suggested it.  To learn more about the difference between String literal and String object, see this article.

Here is a nice image that shows this difference quite well:

Core Java Interview questions


Question 17: What is an Immutable Object? Can you write Immutable Class? (answer)
Immutable classes are Java classes whose objects can not be modified once created. Any modification in Immutable object results in a new object. For example, String is immutable in Java.

Mostly Immutable classes are also final in Java, in order to prevent subclasses from overriding methods, which can compromise Immutability. You can achieve the same functionality by making members non-final but private and not modifying them except in the constructor. 

Apart from the obvious, you also need to make sure that, you should not expose the internals of an Immutable object, especially if it contains a mutable member. Similarly, when you accept the value for the mutable member from the client e.g. java.util.Date, use clone() method keep a separate copy for yourself, to prevent the risk of malicious client modifying mutable reference after setting it. 

The Same precaution needs to be taken while returning value to a mutable member, return another separate copy to the client, never return original reference held by Immutable class. You can see my post How to create an Immutable class in Java for step-by-step guides and code examples. 



Question 18: Give the simplest way to find out the time a method takes for execution without using any profiling tool? (answer)
Read the system time just before the method is invoked and immediately after the 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 a considerable amount of processing


Question 19: Which two methods do you need to implement to use any Object as a key in HashMap? (answer)
In order to use any object as a Key in HashMap or Hashtable, it must implement the equals and hashcode method in Java. Read How HashMap works in Java for a detailed explanation of how the equals and hashcode method is used to put and get an object from HashMap. 



Question 20: How would you prevent a client from directly instantiating your concrete classes? For example, you have a Cache interface and two implementation classes MemoryCache and DiskCache, How do you ensure there is no object of these two classes is created by the client using the new() keyword.

I leave this question for you to practice and think about before I give the answer. I am sure you can figure out the right way to do this, as this is one of the important decisions to keep control of classes in your hand, great from a maintenance perspective.

I am also very grateful to my readers who have generously contributed several good questions from Java Interviews for both beginners and experienced developers alike. I have already answered many of these questions in this blog and you can easily find a relevant post by using the search box at the top right corner of this page.


Other Interview Questions You May Like 

Thanks for reading this article so far. If you like these interview questions then please share them with your friends and colleagues. If you have any questions or feedback then please drop a comment.

P. S. - If you are new to Java world and looking for some free resources to kick-start your Java development journey, then I also suggest you check out this list of free Java courses for beginners on Medium.  

71 comments :

Scott said...

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();

javin paul said...

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

javin paul said...

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.

javin paul said...

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

javin paul said...

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

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;
}

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 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.

Anonymous said...

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



Also, your english is terrible.

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 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.

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 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.

Unknown said...

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.

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, unix etc. UI types, created objects are related by domain.

Jennifer said...

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.

Anonymous said...

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.

seenu said...

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

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 questions are little tough to me.

Anonymous said...

..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

Anonymous said...

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.

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 of these banks please share.

Vineet said...

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.

Buddhiraj said...

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 ?

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.

Anand Vijayakumar said...

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

Javin said...

@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

Anonymous said...

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?

Bhanu P. said...

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.

Prabha kumari said...

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

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 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.

Putti said...

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

Sonam said...

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.

Unknown said...

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

Anonymous said...

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.

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 point to object in heap.

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

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.

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.

garima said...

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.

Anonymous said...

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.

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 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

Unknown said...

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

Peter said...

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.

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.

Deepak said...

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

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.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

Anonymous said...

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

Anonymous said...

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

Unknown said...

@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.

Anonymous said...

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

Gautam said...

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

Unknown said...

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

Anonymous said...

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

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 waited due to context switch. Below approach should be used:

ThreadMXBean threadMX = ManagementFactory.getThreadMXBean();

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

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

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 s will 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 will create a new String object
in normal (nonpool) memory, and s will refer to it. In addition, the literal "abc" will
be placed in the pool.
----------------------

Xhotery said...

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

Anonymous said...

I agree with Xhotery, this questions are from 2012 and 2011 years, now it's 2013. In order to crack Java interview 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 even bit of functional programming knowledge is required. In recent Java interviews, peoples are asking about lambdas of Java 8 and How it's going to improve performance, questions about functional interface and new date and time library. Even questions from Java 7 e.g. try with resource and String in Switch are quite popular nowadays. So be more advanced and prepare relevant questions, which is popular in 2013, not two years back.

Anonymous said...

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

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 several technologies 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 not possible to disable reflexion most of the times.

10. In Java a java-core environment, singleton means single instance per class loader (not per application!). In other 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 including method 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 the JIT does at runtime dramatically changes the execution time after a number of method calls. Actually, the first call of a method is the wrongest way to measure its execution time.

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 to object in heap.

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

Surendar said...

Hi,

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

cbp said...

First of all, thank you so much for putting this page together. It is a great starting point to refresh some concepts before going into an interview. I would also recommend that everyone study the book 'Effective Java' 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 the getInstance() method.

//ALL YOU NEED
public 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 shared object reference without synchronization is to erroneously see a stale value (in this case, null); in that case the DCL idiom compensates for this risk by trying again with the lock held. But the worst case is actually considerably worse - it is possible to see a current value of the reference but stale values for the object's state, meaning that the object could be seen to be in an invalid or incorrect state." -Java Threads In Practice p. 214

Anonymous said...

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

Anonymous said...

Hi all
i have an interview in RAK bank for the post java developer..if anyone know about the interview questions please help

Anonymous said...

Can someone tell me, why does collection use objects not primitive types. While objects take more space to work.

Anonymous said...

hey @Javin - Sting pool is in method area and not in permgen space...
Thanks,
Pramod p

Javin said...

Thanks Guys, You may also like to see my list of 50 multithreading questions, let me know if you find it good. Cheers

chaitu said...

Question nineteen : time can be computed by system.nanoTime() if milliseconds returned are zero
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 amount of processing


akshaytank said...

Hi ,
I have doubt regarding question no : 3
Does all property of Immutable Object needs to be final?

What if we write main method in the class itself. Here we can access the private member of that class by creating object of the class. In this case it is not immutable class.

Anonymous said...

Here is another good list of curated core Java interview questions

Akshay said...

Recently I appeared for some service based companies like Sapient, Cognizant, Infosys and Mindtree for a senior Java developer role, soem of the question I could reemember from those interviews are :
Explain JVM architecutre?
Difference between interface and abstract class?
How Garbage collector works?
How HashMap works?
Does Java support multiple inheritance?
Difference between factor and dependency injection?
Explain Visitor design pattern?
What is type erasure? How generics works?

Thanks to Javarevisited , it helped me a lot to referesh my concepts.

Anonymous said...

Simple but useful questions, for more Java interview questions from last 5 years, see this list of 133+ Java questions wiht answers

Anonymous said...

For question number 5 regarding Singleton, I really don't understand why there is no private constructor defined as the class can still be instantiated using default constructor?

Aniket Thakur said...

When you say
"From Java 8 onwards though collision will not impact performance as much as it does in earlier versions because after a threshold the linked list will be replaced by the binary tree, which will give you O(logN) performance in the worst case as compared to O(n) of linked list.
"

I hope you mean binary search tree. Not sure how else it can be O(logN).

javin paul said...

@Aniket, that comment was with respect to HashMap and LinkedHashMap as they are using binary tree instead of linked list to store collided elements in the bucket. Please see my post How HashMap and LinkedHahsMap handles collision in Java

Post a Comment