Java Tricky Questions
1) Why String is immutable in java?
Three reasons:
1) String pool requires string to be immutable otherwise shared reference can be changed from anywhere.
2) security because string is shared on different area like file system, networking connection, database connection , having immutable string allows you to be secure and safe because no one can change reference of string once it gets created. if string had been mutable anyone can surpass the security be logging in someone else name and then later modifying file belongs to other.
2) Why multiple inheritances are not supported in Java?
Short answer is because of diamond pattern, diamond pattern creates ambiguity and make problem for compiler. Anyway java supports multiple inheritances via interfaces.I think more convincing reason for not supporting multiple inheritance is complexity involved in constructor chaining, casting etc rather than diamond problem.
3) How to detect deadlock and fix it?
when two or more threads waiting for each other to release lock and get stuck for infinite time , situation is called deadlock
4) When a singleton is not singleton in Java?
Many cases like Serialization, RMI, Clasloader loading multiple instance etc.
5) Difference between noclassdeffounderror and classnotfoundexception?
As per my experience java.lang.NoClassDefFoundError occurs when a particular class was present during Compile time but not available during run time by any reason, while ClassNotFoundException comes when class loaded explicitly during runtime.
6) Why equals() method must be compatible with compareTo in java ?
compareTo method must be compatible with equals method in Java i.e. if two objects are equal via equals method compareTo method must return “0” for them, failing this may result in some subtle bug when you store those objects in collection class like arraylist in java.
7) Explain Race condition in JAVA?
Race conditions in Java are always tricky to find and solve. Not many people know about it that hashmap could run into race condition if it would be modified by two threads simultaneous and one thread tries to re-siz or rehash the map because of capacity crossing threshold value. Since hashmap maintains a linked list of element in bucket and while copying from one hashmap to other or old to new order of linked list got reversed, which could result in infinite loop if two threads are doing resizing at same time?
Otherwise some set e.g. TreeSet and TreeMap which uses compareTo will not able to detect duplicates and allow duplicate inside set.
8) Can we call static method with null object?
I bet this is the most tricky Java interview question I ever encountered. Yes we can call because static method is bound at compile time and only type of variable is used for static binding not the value of object. It’s not a good practice to call static method by instance, always call static method in Java by using class name like Math.max()
9) How does volatile variable works in Java?
Another seriously senior developer question in Java and tricky part of this question is change in volatile variable in Java 5. Though volatile is just a keyword its probably most confusing one in core Java. Volatile guarantee not just limited to the variable but also all the variables two threads see known as “happens before” relationship. Another important aspect of making a variable volatile is that compiler will not reorder the variable when switching from client to server configuration or while performing optimization. Read What is volatile variable in Java and How it works for detailed information on volatile variable in Java
10) How to detect memory leak in Java.
This is the most tricky Java interview question, there is no sure sort answer but you can use profile and memory dump to find memory leak in Java. JConsole can also help to provide graph of memory usage which can show pattern for memory leak.
11)What’s wrong using HashMap in the multi-threaded environment? When get() method go to the infinite loop?
Well, nothing is wrong, it depending upon how you use. 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 which contains configuration properties. The real problem starts when at least one of that thread 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 infinite loop, that’s why either you should use Hashtable or ConcurrentHashMap, later is better.
12. 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 increase 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.
13)Does all property of Immutable Object needs to be final?
Not necessary, as stated above you can achieve the same functionality by making member as non-final but private and 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 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.
14: 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 character long, can prevent 1GB character array from garbage collection, by holding a strong reference.

This issue is fixed in Java 1.7, where original character array is not referenced anymore, but that change also made the creation of substring bit costly in terms of time. Earlier it was in the range of O(1), which could be O(n) in worst case on Java 7.
16: How do you handle error condition while writing stored procedure or accessing stored procedure from java?
This is one of the tough Java interview questions 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 an error code if some operation fails but if stored procedure itself fails than catching SQLException is the only choice.
Question 7 : 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 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)
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.
18)What will be the problem if you don’t override hashCode() method?
If you don’t override 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 invariant of HashMap class because they are not supposed to allow duplicate keys. When you add the object using put() method, it iterate 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 hashcode is not overridden.
19: How do you avoid deadlock in Java?
You can avoid deadlock by breaking circular wait condition. In order to do that, you can make arrangement in the code to impose the ordering on acquisition and release of locks. If lock will be acquired in a consistent order and released in just opposite order, there would not be a situation where one thread is holding a lock which is acquired by other and vice-versa. See the detailed answer for the code example and more detailed explanation.
20: Where does equals() and hashCode() method comes in the picture during the get() operation?
This core Java interview question is a follow-up of 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 it’s hashcode method is called to calculate bucket location. Since a bucket may contain more than one entry as 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.
21: What is Immutable Object? Can you write Immutable Class?
Immutable classes are Java classes whose objects can not be modified once created. Any modification in Immutable object results in the 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 member as non-final but private and not modifying them except in constructor.
Apart from obvious, you also need to make sure that, you should not expose the internals of Immutable object, especially if it contains a mutable member. Similarly, when you accept the value for the mutable member from 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 guide and code examples.