Basic java interview questions and answers

Can I store a double value in a long variable without casting? 
No, you cannot store a double value into a long variable without casting because the range of double is more  that long and you we need to type cast. It's not dificult to answer this question but many develoepr get it wrong due to confusion on which one is bigger between double and long in Java.

What will this return 3*0.1 == 0.3? true or false? 
This is one of the really tricky questions. Out of 100, only 5 developers answered this question and only of them have explained the concept correctly. The short answer is false because some floating point numbers can not be represented exactly.

Which one will take more memory, an int or Integer?
An Integer object will take more memory an Integer is the an object and it  store meta data overhead about the object and int is primitive type so its takes less space.

Can we use String in the switch case? 
Yes from Java 7 onward we can use String in switch case but it is just syntactic sugar. Internally string hash code is used for the switch. See the detaiedl answer for more explanation and discussion.

What is constructor chaining in Java? 
When you call one constructor from other than it's known as constructor chaining in Java. This happens when you have multiple, overloaded constructor in the class.


What is the size of an int variable in 32-bit and 64-bit JVM?
The size of int is same in both 32-bit and 64-bit JVM, it's always 32 bits or 4 bytes.

A difference between WeakReference and SoftReference in Java?
Though both WeakReference and SoftReference helps garbage collector and memory efficient, WeakReference becomes eligible for garbage collection as soon as last strong reference is lost but SoftReference even thought it can not prevent GC, it can delay it until JVM absolutely need memory.

How do WeakHashMap works? 
WeakHashMap works like a normal HashMap but uses WeakReference for keys, which means if the key object doesn't have any reference then both key/value mapping will become eligible for garbage collection.

Can you guarantee the garbage collection process? (answer)
No, you cannot guarantee the garbage collection, though you can make a request using System.gc() or Runtime.gc() method.

The difference between List, Set, Map, and Queue in Java? 
The list is an ordered collection which allows duplicate. It also has an implementation which provides constant time index based access, but that is not guaranteed by List interface. Set is unordered collection which

Difference between poll() and remove() method?
Both poll() and remove() take out the object from the Queue but if poll() fails then it returns null but if remove fails it throws Exception.

Resources:

Java interview questions

Best java training institute in chennai