top of page

Java interview questions

Q1 What’s wrong with using HashMap in the multi-threaded environment? When get() method go to the infinite loop?

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.


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

Q3 Does all property of Immutable Object needs to be final?

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. 

Q4 How does substring () inside String works? 

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


Q5 Can you write critical section code for the singleton?

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

Q6 How do you handle error conditions while writing stored procedures or accessing stored procedures from java?

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.

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

Q8  What is the difference between a factory and abstract factory patterns?

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. 

Q9 What is Singleton? is it better to make the 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 the enum and double checked locking which is the purpose of this Java interview question.

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

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.

bottom of page