Help Us Improve. Please let us know if you were asked any of these questions.

More Questions

Java - Interview Questions and Answers for Senior Java Developer / Java Experts / Principal Developers

Q1.  There are two objects a and b with same hashcode. I am inserting these two objects inside a hashmap.


where a.hashCode()==b.hashCode()

Now tell me how many objects will be there inside the hashmap?

Ans. There can be two different elements with the same hashcode. When two elements have the same hashcode then Java uses the equals to further differentation. So there can be one or two objects depending on the content of the objects.

Q2.  Difference between long.Class and Long.TYPE ?

Ans. They both represent the long primitive type. They are exactly the same.

Q3.  Can constructors be synchronized in Java ?

Ans. No. Java doesn't allow multi thread access to object constructors so synchronization is not even needed.

Q4.  What is the use of hashcode in Java ?

Ans. Hashcode is used for bucketing in Hash implementations like HashMap, HashTable, HashSet etc. The value received from hashcode() is used as bucket number for storing elements. This bucket number is the address of the element inside the set/map. when you do contains() then it will take the hashcode of the element, then look for the bucket where hashcode points to and if more than 1 element is found in the same bucket (multiple objects can have the same hashcode) then it uses the equals() method to evaluate if object are equal, and then decide if contain() is true or false, or decide if element could be added in the set or not.

Q5.  Why is String immutable in Java ?

Ans. 1. String Pool

When a string is created and if the string already exists in the pool, the reference of the existing string will be returned, instead of creating a new object. If string is not immutable, changing the string with one reference will lead to the wrong value for the other references.

2. To Cache its Hashcode

If string is not immutable, One can change its hashcode and hence not fit to be cached.

3. Security

String is widely used as parameter for many java classes, e.g. network connection, opening files, etc. Making it mutable might possess threats due to interception by the other code segment.

Q6.  Which are the different segments of memory ?

Ans. 1. Stack Segment - contains local variables and Reference variables(variables that hold the address of an object in the heap)
2. Heap Segment - contains all created objects in runtime, objects only plus their object attributes (instance variables)
3. Code Segment -  The segment where the actual compiled Java bytecodes resides when loaded

Q7.  Does garbage collection guarantee that a program will not run out of memory?

Ans. Garbage collection does not guarantee that a program will not run out of memory. It is possible for programs to use up memory resources faster than they are garbage collected. It is also possible for programs to create objects that are not subject to garbage collection

Q8.  Describe what happens when an object is created in Java ?

Ans. 1. Memory is allocated from heap to hold all instance variables and implementation-specific data of the object and its superclasses. Implemenation-specific data includes pointers to class and method data.
2. The instance variables of the objects are initialized to their default values.
3. The constructor for the most derived class is invoked. The first thing a constructor does is call the constructor for its superclasses. This process continues until the constructor for java.lang.Object is called,
as java.lang.Object is the base class for all objects in java.
4. Before the body of the constructor is executed, all instance variable initializers and initialization blocks are executed. Then the body of the constructor is executed. Thus, the constructor for the base class completes first and constructor for the most derived class completes last.

Q9.  Describe, in general, how java's garbage collector works ?

Ans. The Java runtime environment deletes objects when it determines that they are no longer being used. This process is known as garbage collection. The Java runtime environment supports a garbage collector that periodically frees the memory used by
objects that are no longer needed. The Java garbage collector is a mark-sweep garbage collector that scans Java's dynamic memory areas for objects, marking those that are referenced. After all possible paths to objects are investigated, those objects that are not marked (i.e. are not referenced) are known to be garbage and are collected.

Q10.  Can I import same package/class twice? Will the JVM load the package twice at runtime?

Ans. One can import the same package or same class multiple times. Neither compiler nor JVM complains wil complain about it. And the JVM will internally load the class only once no matter how many times you import the same class.

Q11.  Different types of memory used by JVM ?

Ans. Class , Heap , Stack , Register , Native Method Stack.

Q12.  What is a class loader ? What are the different class loaders used by JVM ?

Ans. Part of JVM which is used to load classes and interfaces.

Bootstrap , Extension and System are the class loaders used by JVM.

Q13.  Difference between loadClass and Class.forName ?

Ans. loadClass only loads the class but doesn't initialize the object whereas Class.forName initialize the object after loading it.

Q14.  What are the design considerations while making a choice between using interface and abstract class ?

Ans. Keep it as a Abstract Class if its a "Is a" Relationsship and should do subset/all of the functionality. Keep it as Interface if its a "Should Do" relationship.

Q15.  What are various types of Class loaders used by JVM ?

Ans. Bootstrap - Loads JDK internal classes, java.* packages.

Extensions - Loads jar files from JDK extensions directory - usually lib/ext directory of the JRE

System  - Loads classes from system classpath. 

Q16.  What is ThreadFactory ?

Ans. ThreadFactory is an interface that is meant for creating threads instead of explicitly creating threads by calling new Thread(). Its an object that creates new threads on demand. Using thread factories removes hardwiring of calls to new Thread, enabling applications to use special thread subclasses, priorities, etc.

Q17.  What is PermGen or Permanent Generation ?

Ans. The memory pool containing all the reflective data of the java virtual machine itself, such as class and method objects. With Java VMs that use class data sharing, this generation is divided into read-only and read-write areas. The Permanent generation contains metadata required by the JVM to describe the classes and methods used in the application. The permanent generation is populated by the JVM at runtime based on classes in use by the application. In addition, Java SE library classes and methods may be stored here.

Q18.  What is metaspace ?

Ans. The Permanent Generation (PermGen) space has completely been removed and is kind of replaced by a new space called Metaspace. The consequences of the PermGen removal is that obviously the PermSize and MaxPermSize JVM arguments are ignored and you will never get a java.lang.OutOfMemoryError: PermGen error.

Q19.  What is the difference between System.out ,System.err and

Ans. System.out and System.err both represent the monitor by default and hence can be used to send data or results to the monitor. But System.out is used to display normal messages and results whereas System.err is used to display error messages and represents InputStream object, which by default represents standard input device, i.e., keyboard.

Q20.  Do you think that Java should have had pointers ?

Ans. Open ended Questions.

Q21.  what is covariant return type? 

Ans. co-variant return type states that return type of overriding method can be subtype of the return type declared in method of superclass. it has been introduced since jdk 1.5

Q22.  Why Char array is preferred over String for storing password?

Ans. String is immutable in java and stored in String pool. Once it’s created it stays in the pool until unless garbage collected, so even though we are done with password it’s available in memory for longer duration and there is no way to avoid it. It’s a security risk because anyone having access to memory dump can find the password as clear text.

Q23.  Why String is popular HashMap key in Java?

Ans. Since String is immutable, its hashcode is cached at the time of creation and it doesn’t need to be calculated again. This makes it a great candidate for key in a Map and it’s processing is fast than other HashMap key objects. This is why String is mostly used Object as HashMap keys.

Q24.  What does String intern() method do?

Ans. intern() method keeps the string in an internal cache that is usually not garbage collected.

Q25.  How substring() method of String class create memory leaks?

Ans. substring method would build a new String object keeping a reference to the whole char array, to avoid copying it. Hence you can inadvertently keep a reference to a very big character array with just a one character string.

Q26.Difference between new operator and Class.forName().newInstance() ?

Ans. new operator is used to statically create an instance of object. newInstance() is used to create an object dynamically ( like if the class name needs to be picked from configuration file ). If you know what class needs to be initialized , new is the optimized way of instantiating Class.

Q27.  Is JVM a overhead ? 

Ans. Yes and No. JVM is an extra layer that translates Byte Code into Machine Code. So Comparing to languages like C, Java provides an additional layer of translating the Source Code.

C++ Compiler - Source Code --> Machine Code
Java Compiler - Source Code --> Byte Code   ,  JVM - Byte Code --> Machine Code

Though it looks like an overhead but this additional translation allows Java to run Apps on all platforms as JVM provides the translation to the Machine code as per the underlying Operating System. 

Q28.  Can you provide some implementation of a Dictionary having large number of words ? 

Ans. Simplest implementation we can have is a List wherein we can place ordered words and hence can perform Binary Search.

Other implementation with better search performance is to use HashMap with key as first character of the word and value as a LinkedList.

Further level up, we can have linked Hashmaps like ,

hashmap {
a ( key ) -> hashmap (key-aa , value (hashmap(key-aaa,value)
b ( key ) -> hashmap (key-ba , value (hashmap(key-baa,value)
z( key ) -> hashmap (key-za , value (hashmap(key-zaa,value)

upto n levels ( where n is the average size of the word in dictionary.

Q29.  What will be the output of this code ?

enum Day {

public class BuggyBread1{
    public static void main (String args[]) {
     Set<Day> mySet = new TreeSet<Day>();
     for(Day d: mySet){


Only one FRIDAY will be printed as Set doesn't allow duplicates.

Elements will be printed in the order in which constants are declared in the Enum. TreeSet maintains the elements in the ascending order which is identified by the defined compareTo method. compareTo method in Enum has been defined such that the constant declared later are greater than the constants declared prior. 
 Stay Updated with Java Posts directly to your mailbox.
Enter your email address:

Subscribe to Java News and Posts. Get latest updates and posts on Java from
Enter your email address:
Delivered by FeedBurner
comments powered by Disqus


Try our new Java Interview Questions Search Tool.

There are more than 1000 questions with practice tests.

It's updated daily and It's Awesome.


Try our new Java Practice Test tool.

There are more than 200 questions and expanding quickly. It's updated daily and It's Awesome.