Java Interview Questions

These Java interview questions are the most frequently asked by recruiters and employers.

What happens if you use a primitive local variable before initializing it?


The Java compiler will throw an error. Local variables do not get initialized to any default value even if they are primitives like int or boolean. Every local variable needs to be assigned a value before it can be accessed.

When is memory allocated for static members?


All instantiation and memory allocation for static variables for all classes in the program is done before running the main method.

Is super class instantiated when subclass is instantiated?


No, the object created is an instance of both the super class and subclass, but there’s no separate instance of the super class. In order to create a separate instance of the super class it must be instantiated directly.

The constructor of the super class is always called when the subclass is instantiated, although which constructor of the super c

...

What are exceptions? What is the difference between checked and unchecked exceptions?


Exceptions are errors in a program which disrupt the normal flow of code execution.

Checked exceptions are those which can be expected by the program due to various conditions, such as bad user input. These are handled using a try/catch block, and the flow of code execution is still in control of the programmer. If checked exceptions are not hand

...

Should you use external libraries in your code? What are the benefits and drawbacks? What precautions can be taken?


External libraries are extremely helpful when writing large and complex programs - they save the effort of having to code something which has already been implemented by someone else.

...

What are Immutable Classes in Java? What are Immutable Classes useful for?


Immutable classes are those which cannot be changed once instantiated. The value of the object of an immutable class will always remain the same. Either the value cannot be changed or any change to the vale will result in a new immutable instance. String, Boolean and other primitive wrapper classes are all Immutable. All the variables and the c

...

Are two Strings containing identical text always equal in every way, every time?


No. If the Strings are instantiated using the String constructor, then they will have the same value but will reference distinct, and therefore different, objects.

Example:

So, writing S1 == S2 will be false when either S1, S2, or both are created using the String constructor, because they are pointing to different objects. Using `S1.equa

...

What Collection would you use to iterate with insertion order and also have O(1) lookup time? Are there any drawbacks to using this Collection?


LinkedHashSet provides an average O(1) lookup time and also maintains the entries in a doubly-linked list, which can be used to maintain insertion order. The only drawback in this case is that we cannot have duplicates in the Collection because it is a Set.

What happens when one thread modifies a HashMap while another thread is iterating the same map? What is the correct way to do this?


A HashMap is not a synchronized Map, meaning that it is not thread-safe. If a HashMap is modified by a thread while another thread is iterating it, a ConcurrentModificationException will be thrown.

There are two possible ways to do this correctly:

...

Explain the difference between Heap and Stack in Java.


The Heap Memory in Java is the space used by the JVM Runtime to allocate memory and store objects used throughout the program. Heap objects are shared across the entire program. The Heap has a special space called PermGen which is used for holding metadata about user classes and some other advanced functions.

The Stack Memory is used by the JVM fo

...

What parts of each line of the following code will be stored in the Heap and what parts will be stored in the Stack?


Before the main method is called, the program allocates Heap space and puts all the runtime classes and class-level objects into the Heap.

Line 1 - Creates stack space for the main method. The String arguments are in the Heap in the PermGen area, while references to the strings are stored in the Stack.

Line 2 - Puts the primitive x on the Sta

...

Explain why Java is Pass-by-Value and not Pass-by-Reference. Give an example.


Pass-by-value is when the reference to an object is copied to a new variable.

Pass-by-reference is when a reference to an object is passed directly to the other method.

When a method is called in Java, new Stack space is allocated for the method and all variables in the arguments are copied to the new Stack block.

Example:

In the first print

...

Is it recommended to use the final keyword in method parameters?


Yes, Java is a Pass-by-Value language, so all the variables are local to the current method. Changing the value of the method parameter will not result in any changes in the calling method. To avoid mistakes and make the code more readable, marking the method parameters final is the best approach. This also makes it mandatory for the developer to e

...

How many servlet instances are created when multiple requests arrive simultaneously?


Only one Servlet instance is created at the time of the first call in the program. This instance is reused for all further requests even if multiple requests arrive simultaneously.

Describe the two different types of Servlets.


The two types of Servlets are GenericServlet and HttpServlet.

GenericServlet is a protocol-independent Servlet used as a base class for writing non-HTTP servlets. It provides basic functionality for writing a Servlet.

HttpServlet is an extension of GenericServlet that is used for writing Web-based HTTP servlets. It is used for HTTP methods like

...

Does a HashMap Key object have to be Immutable?


HashMap calculates the location of an object based on the value of the hashCode function. If the values used to calculate the hashCode of an object change after it is inserted in the HashMap, this will result in the Key returning a different address than the one originally used. In this case, the HashMap cannot locate the original Key and the objec

...

What is the difference between: final, finally, finalize?


final is a keyword which can be used on a variable, class, or method.

finally is a code block that is guaranteed to run after a throws block, even if the exception is not thrown.

finalize is a method

...

What are Generics in Java?


Generics are a feature that allow a class to be parameterized into sub-types. Generics provide compile-time safety and prevent runtime typecasting errors resulting in ClassCastException. Without generics, a user is forced to use the lowest common base-class and then typecast the object, which is highly error-prone and has no type-safety.

Can a base-type access properties in its sub-types?


When a class is inherited, the base type can have properties shared by all sub-types, and each sub-type can have their specific properties. The sub-type properties cannot be accessed by other sub-types of the same Generic object or even in the base-type.

What is Polymorphism?


Polymorphism is the ability to have one interface for accessing several implementations. The interface determines the requirements for the implementation. The implementation can be accessed using the interface because it abides to the interface.

What is method overloading and method overriding?


Method overloading is having several forms of the same method, each differing in the formal argument list.

Method overriding is when the exact same method definition is created in a sub-class, which results in hiding the base-class method.

What happens if the main method is not static?


If a program has a main method without the static keyword, it will compile, but will throw a Runtime Exception with NoSuchMethodError.

What is the significance of the Garbage Collector in Java? How does it work?


The Garbage Collector is an automatic memory management tool that reclaims memory by removing unused heap objects.

...

Explain the uses of this keyword.


this is a self-reference to the current instance of the class. It can be used to invoke the constructor, to reference a class-level variable or method, or to refer to or pass the object instance.

When this is used for calling the constructor within another constructor, it is called constructor chaining. It must be the first line of the constru

...

Can you create an object of a class within the same class? Can this lead to an error?


Yes, you can instantiate a class within itself. Example:

The line commented as Error line is an example of self-object instantiation leading to an error. In this case, the JVM will allocate stack space on each constructor call, and the stack will soon run out of space leading to a StackOverflowError, a common recursion problem.

Why won't the following code sample compile and how would you fix it?


This will raise a compilation error. It is incorrect to pass a List<String> to a method accepting List<Object>. A List<Object> can accept Strings, but t1 can only accept List<Object>.

Either ls should be changed to List<Object>, or lo should be made Generic: List<? extends Object> lo

What is super? Are the following uses of super correct?


The super keyword is used to reference the parent class and methods of the parent class. super can be used to invoke the constructor of the parent class as well. In this case, it must be the first line of code. If there is no default constructor in the base class, then it is mandatory to call one of the base class parameterized constructors.

...

What are the automated memory management features of Java?


In comparison to other languages, the Java Runtime has several automated memory management features to improve the safety, reliability, efficiency, and ease of programming.

...

Describe a potential way of creating a memory leak in Java. Give an example.


Because Java has automated memory management, it precludes code errors relating to allocation of memory for objects and reclaiming memory from objects. This prevents user errors arising due to incorrect code for memory management, but it does not avoid design flaws that can result in memory leaks.

Example of Design flaw:

We are required to implem

...

If a super class method is throwing RuntimeException, can it be overriden in a subclass method throwing NullPointerException?


In Java, it is possible to override a method with a different throws signature if the base class method only throws Runtime Exception (unchecked exceptions). If the base class method throws checked exceptions, then the subclass method has to have one of the following:

What is type erasure?


The Type information used for Generic objects is only available at compile time. The compiler removes all the type information when converting to byte-code. This makes the type information unavailable at Runtime and the Generic type is converted to Raw type. The compiler provides checks at compile time to prevent runtime errors for incorrect type i

...

Is the following code compile-time and run-time safe?


Yes, this code is compile-time and run-time safe.

I and K are Generic type parameters used to ensure type safety.

The extends keyword in the first line defines the scope of the I parameter. The I parameter can only be a sub-type of List of type K. K by default extends Object.

The second extends keyword is used for inheriting c

...

What is the use of the volatile keyword in Java? What is the happens-before guarantee?


The volatile keyword is used in multi-threaded programs. It indicates that a variable can be updated by multiple threads. This means that the value of the variable cannot be cached locally and must be directly accessed from main memory every time. volatile variables are not serializable.

The happens-before guarantee for volatile variables ca

...

Explain instruction reordering. In what context can instruction reordering create problems? How can it be fixed?


Instruction reordering is when the execution order of the code is changed by the JVM at compile time or run time. This is done to optimize the code. Instruction reordering guarantees program order execution. This means that two statements which are related will have a happens-before relation, but two unrelated statements can be executed out-of-orde

...

Looking for developers?

Want to learn more about Gigster? Enter your email and we'll be in touch.