Top Interview Questions on Core Java

Which are the two methods that you need to implement for key Object in HashMap ?

You need to override equals() and hashcode() methods of a class whose objects you want to use as Key in a hashmap.

What is an immutable object? Can you write an immutable object ?

Immutable classes are Java classes whose objects cannot be modified once they are created. Any modification in immutable object will result into new object. For example 'isString' 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 on immutability. You can achieve same functionality by making a member which is not final but private and cannot be modified except in constructor.

What is the difference between creating String as new() and literal?

When we create a string with new() operator, it's created in heap and not added into string pool whereas string created using literal is added in the string pool itself which exists in PermGen area of heap.

The above shown example will not put the object in string pool and so we need to call String.intern() method which is used to put them into string pool explicitly. This will only happen when you make a string object as string literal e.g. String s = "Javabykiran_Test". Java will automatically add this into the string pool.

What is the difference between StringBuffer and StringBuilder in Java ?

This is a classic Java question which some people find it quite tricky whereas some consider it very easy. StringBuilder in Java was introduced in Java 5 and the only difference between Stringbuffer and StringBuilder is that Stringbuffer methods are synchronized while the latter one is non-synchronized.

Write a code in order to find the first non-repeating character in the String.

This is another good question related to Java asked in interviews. This kind of question is mainly asked by Amazon and other such equivalent companies.

What is the difference between an ArrayList and a Vector ?
  • Difference between Vector and Arraylist is one of the most common Core Java Interview questions you will come across in Collection. This question is mostly asked at an initial stage by the Interviewers before testing the deep knowledge regarding Collection.

  • Vectors are synchronized. Any method that touches the Vector's contents is thread safe. ArrayList, on the other hand, is unsynchronized, making them, therefore, not thread safe.

  • Vector and ArrayList classes are implemented using dynamically resizable array that enables fast random access and list traversal similar to that while using an ordinary array.

  • ArrayList supports dynamic arrays in which changes can be made as per requirement that is ArrayList can be dynamically increased or decreased in size.

Learn in Detail by our Experts

How can you handle error condition while writing stored procedure or accessing stored procedure from java ?

This is one of the toughest questions of Java usually asked in an interview which is open for all. A friend of mine was unaware of the answer to this question and also did not hesitate in sharing this with me. According to me stored procedure returns an error code only if some operation fails but if stored procedure itself fails than catching SQLException is the only choice left.

What is the difference between Executor.submit() and Executer.execute() method ?
  • There is a bit difference when looking at exception handling. If your tasks throw an exception and also if it has been submitted then this exception will go to the uncaught exception handler (if you don't provide one explicitly, then the default one will just print the stack trace to System.err).

  • If you have submitted the task with any thrown exception, checked exception or not, it then becomes part of the task's return status.

  • For a task that has been submitted with submit and it terminates with an exception, then Future.get will again throw this exception, wrapped in an ExecutionException.

What is the difference between 'factory' and 'abstract factory' pattern?

Abstract Factory provides an extended level of abstraction. Consider different factories where each is extended from an Abstract Factory and becomes 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 particular genre.

What is Singleton? Is it better to make whole method synchronized or only critical section synchronized ?

Singleton in Java is a class which has just one instance in whole Java application. For instance java.lang.Runtime is a Singleton class. Creating Singleton was initially tricky in Java 4 but it became easier with inception of Enum by Java 5.

Can you write critical section code for singleton ?

This core Java question is follow up of previous question. The candidate is expected to write Java singleton using double checked locking. Remember to use volatile variable in order to make Singleton thread safe.

Can you write code for iterating over hashmap in Java 4 and Java 5 ?

It is a bit tricky but you can perform this task using the 'while' loop and 'for' loop.

When do you override hashcode and equals() ?

We can override hashcode whenever necessary and especially when we want to do an equality check or when we want to use our object as key in HashMap.

Which kind of problem you will encounter if you don't override hashcode() method ?

You will not be able to recover your object from HashMap if that is used as key in HashMap.

Is it better to synchronize critical section of getInstance() method or whole getInstance() method ?

Critical section is better because if we lock the whole method than every time when someone calls this method it will have to wait even though we are not creating any object.

What is the difference when a String gets created using literal and new() operator ?

When we create string with new() operator it gets created in heap and is not added into string pool while String created using literal operator are added in the String pool itself which exists in Perm area of heap.

If one does not override hashcode() method then does it have any performance implication ?

This is a good question and is open to all. According to me a poor hashcode function will result into frequent collisions in HashMap which eventually increases time for adding an object into Hash Map.

What is wrong in using HashMap in multithreaded environment? When wil get() method go into an infinite loop ?

This is another good question. The get() method will go into an infinite loop during concurrent access and re-sizing.

What do you understand by thread-safety ? Why is it required and how can it be achieved in Java Applications ?
  • Java Memory Model defines the legal interaction of threads with the memory in a real computer system. In another way we can say that it describes which behaviors are legal in multi-threaded code. It determines when a thread can reliably see the write method done on variables by other threads. It defines semantics for volatile, final & synchronized which guarantees the visibility of memory operations across the Threads.

  • Let's first discuss about Memory Barrier which is the base for the further discussions. There are two type of memory barrier instructions in JMM - read barriers and write barrier.

  • A read barrier invalidates the local memory (cache, registers, etc) and then reads the contents from the main memory, so that changes made by other threads becomes visible to the current Thread.

    A write barrier flushes out the contents of the processor's local memory to the main memory, so that changes made by the current Thread becomes visible to the other threads.

  • JMM semantics for synchronized

    When a thread acquires monitor of an object, by entering into a synchronized block of code, it performs a read barrier (invalidates the local memory and reads from the heap instead). Similarly exiting from a synchronized block as part of releasing the associated monitor, it performs a write barrier (flushes changes to the main memory) Thus modifications to a shared state using synchronized block by one Thread, is guaranteed to be visible to subsequent synchronized reads by other threads. This guarantee is provided by JMM in presence of synchronized code block.

  • JMM semantics for Volatile fields

    Read & write to volatile variables have same memory semantics as that of acquiring and releasing a monitor using synchronized code block. So the visibility of volatile field is guaranteed by the JMM. Moreover afterwards Java 1.5, volatile reads and writes are not reorderable with any other memory operations (volatile and non-volatile both). Thus when Thread A writes to a volatile variable V, and afterwards Thread B reads from variable V, any variable values that were visible to A at the time V was written are guaranteed now to be visible to B.

  • Let's try to understand the same using the following code

What will happen if you call return statement or System.exit on try or catch block ? Will finally block execute?

This is a very common tricky Java question and its considered tricky because many programmers think that 'finally' block always gets executed. This question challenges the concept by putting return statement in 'try' or 'catch' block or calling System.exit from 'try' or 'catch' block. The answer to this question in Java is that 'finally' block will execute even if you put 'return' statement in 'try' block or 'catch' block but 'finally' block won't run if you call System.exit form 'try' or 'catch'.

Can you override private or static method in Java ?

This is another common tricky Java question. As mentioned before method overriding is a good topic to ask tricky questions in Java. One cannot override private or static method in Java. If you create a similar method with same return type and same method arguments then it is called method hiding.

What will happen if we put a key object in a HashMap which is already present ?

The difficult part of this Java questions is how does the HashMap works in Java which is also a popular topic to prompt confusing and tricky question in Java. If we put the same key again then it will replace the old mapping because HashMap doesn't allow duplicate keys.

If a method throws NullPointerException in super class then can we override it with a method which throws RuntimeException?

One can throw super class of RuntimeException in overridden method but you cannot do the same if its checked Exception.

How can one ensure that N thread can access N resources without deadlock ?

If one is not well-versed in writing multi-threading code then this becomes a really tricky question for him. This Java question can be tricky even for experienced and senior programmers, who are not really exposed to deadlock and race conditions. Key point here is order, that is if one acquires resources in a particular order and release resources in reverse order one can easily prevent deadlock.

What is the difference between CyclicBarrier and CountDownLatch in Java ?

This concept was introduced from Java 5. The main difference between both of them is that you can reuse CyclicBarrier even if Barrier is broken but you cannot reuse CountDownLatch in Java. You can refer CyclicBarrier vs CountDownLatch in Java for more differences.

Can you access non-static variable in static context?

You cannot access static variable in non-static context in Java. You can refer further as to why you cannot access non-static variable from static method to learn more about this tricky Java question.

Learn More about Interview Questions in our Live Video section