Java Interview Questions and Answers

Q) What is a class in java?
A class is nothing but a blueprint or a template for creating different objects which defines its properties and behaviors
Q) What Is an Object in java?
An object is an instance of a class which has states and behaviors.
Q) What Is an interface in java?
A Java interface is a bit like a class, except a interface can only contain method signatures and fields.
Q) What Is an an Abstract class in java?
A class that is declared with abstract keyword is known as abstract class. It can have abstract and non-abstract methods (concrete methods).
Q) Are JVM's platform independent?
No, JVM's are not platform independent. JVM's are platform specific run time implementation provided by the vendors.
Q) Does Java support multiple inheritance?
No, java doesn't support multiple inheritance.
Q) What is classloader?
The classloader is a part of JVM that is used to load classes and interfaces.There are many types of classloaders, ex:System classloader,Bootstrap classloader, Extension classloader etc.
Q) Can I write static public void main(String args[ ]){ } instead of public static void main(String args[ ]){ } ?
Yes, it works fine, it compiles and runs without any error/exception.
Q) Can we make a constructor final?
No, constructor can't be final.
Q) What does the the expression 1.0/0.0 will return, will it throw Exception or Error?
It will not throw ArithmeticExcpetion and return Double.INFINITY
Q) Why does Java not support operator overloading?
Operator overloading makes the code very difficult to read and maintain .So java doesn't support operator overloading to maintain code simplicity.
Q) What is an abstract method?
An abstract method is a method signature declaration with no body.
Q) What is Abstract classes in Java?
Abstract classes are classes that contain one or more abstract methods. Abstract classes are declared with abstract keyword.
Q) What is Java Development Kit (JDK) ?
Java Development Kit (JDK) is a super set of the JRE. JDK contains Java Run-time Environment (JRE),interpreter(java), a compiler (javac), an archiver (jar), a documentation generator (javadoc) and other tools needed in Java development.
Q) What are the different type of exception in Java ?
Exceptions are two types i.e. Checked Exceptions and Unchecked Exceptions.
Q) In which scenario finally block does not execute ?
If we calls system.exit method before finally block, application exits and finally won't execute.
Q) What is a Instance Variable?
Instance variables are variables declared within a class but outside any method. Instance variables are used by objects to store their states. These variables are instantiated when the class is loaded.
Q) What is a Class Variable?
Class variable must have declared with keyword static and are with in a class but outside any method.
Q) What are Wrapper classes in Java?
Integer, Character, Double, Float, Long, Boolean, Byte, Short are the eight wrapper classes in Java, which are available in side java.lang package. These are classes that allow primitive types(int, char, double, float, long, boolean, byte, short) to be accessed as objects.
Q) What will happen if you put return statement or System.exit() on try or catch block? Will finally block execute?
Yes, Finally block will execute even if you put return statement in try block or catch block, but the finally block won't run if you call System.exit form try or catch.
Q) Can we override private or static method in Java?
We can't override static method in Java, if we create a similar method with same return type and same method arguments in child class then it will hide the super class method, this is known as method hiding.

Similarly we cannot override private method because it is not visible from any other class. We can declared a new method for our subclass that has no relation to the super class method.

Q) What does the the expression 1.0/0.0 will return? Will it throw Exception or Error?
No, it will not throw ArithmeticExcpetion and return Double.INFINITY.
Q) Difference between ArrayList and Vector?
  • When resized ArrayList grows by half of its size but Vector grows doubles the size of itself by default.
  • ArrayList is non-synchronized while Vector is synchronized.
  • ArrayList gives better performance than Vector as it is non-synchronized.
  • Vector use Enumeration and Iterator while ArrayList use only Iterator for traversing.
  • Vector has setSize() method which can set increment size manually, no such method in ArrayList.
Q) Difference between Enumeration and Iterator.

Enumeration can be useful if you want to read the list, while Iterator can be used for read the list as well as manipulate the list. Because Iterator has remove() method.

Enumeration has two methods:



Iterator has three methods:

1. hasNext()

2. next()

3. remove()

Q) Difference between arraylist and linkedlist in java.

ArrayList is index based, so accessing elements are faster as compare to LinkedList because of its get(int index) method.

Addition and deletion with ArrayList is slow as compare to LinkedList, because it uses Array internally, so any add or delete operation makes all the bits to shifted in memory. While LinkedList uses doubly linked list so no bit shifting is required in memory.

Q) When to use LinkedList and when to use ArrayList?

ArrayList gives better performance while searching elements because of its get(int index) method, so if the requirement is mostly for searching elements than go for ArrayList.

While LinkedList give better performance for addition and deletion of elements as compare to ArrayList, because it use doubly linked list internally. So if there is a requirement of frequent addition and deletion than got for LinkedList.

Q) Difference between HashMap and Hashtable in Java.

1. Hashtable is synchronized and thread safe, whereas HashMap is not.

2. HashMap perform better than Hashtable for non-threaded applications.

3. HashMap allows one null key and any number of NULL values but Hashtable does not allow any null keys or values.

4. HashMap object values are iterated by using Iterator where as Hashtable uses both Enumerator and Iterator to iterate the values.

Q) Difference between Serialization and Externalization?

Externalizable interface extends Serializable interface.

Serializable is an marker interface while Externalizable interface we need to implement writeExternal() and readExternal() methods of it.

For Serializable, default serialization process is used, while for Externalizable interface provides us complete control of serialization process as we can implements writeExternal() and readExternal() methods of it.

While implementing Serializable interface, it is recommended to provide a serialVersionUID to avoid class version issues when de-serializing objects. With externalizable interface, there is no need to worry about serialVersionUID because we are expected to provide an implementation of how to read and write objects to the stream.

Serialization Example  Exterialization Example

Q) What is Aggregation in java?

Aggregation represents a HAS-A relationship between two classes,


Let's consider two classes Employee and Address, Employee class has an object of Address class. So Employee can use Address reference to invoke methods on the Address, and get Address behavior.
class Employee{  
   int employeeId;  
   String employeeName;  
   Address address; // Employee has-a address

   //More code....
Q) Difference between Thread and Process in Java?

1. Process has its own memory space while every thread has its own stack in Java but it uses process main memory.

2. Threads are called lightweight processes.

3. Processes are independent of each other while threads are interdependent.

4. Threads exist within a process, every process has at least one thread.

Q) Difference between abstract class and interface in Java?

1. Abstract class can have abstract and non-abstract methods while interface can have only abstract methods.

2. The abstract keyword is used to declare abstract class, interface keyword is used to declare interface.

3. Abstract class doesn't support multiple inheritance while interface supports multiple inheritance.

4. Abstract class can implements interfaces, while interface can't extend an abstract class.

5. Abstract class can have constructor, concrete methods and static methods while interface can't have constructor, concrete methods and static methods.

Q) Difference between synchronized HashMap and ConcurrentHashMap in java?

There is no locking at the object level for ConcurrentHashMap while SynchronizedHashMap lock the entire map object.

As ConcurrentHashMap will lock only portion of the data which are being updated while other portion of data can be accessed by other threads. However, SynchronizedHashMap will lock all the data while updating, other threads can only access the data when the lock is released.

Every read/write operation needs to acquire lock for SynchronizedHashMap but for ConcurrentHashMap reads can happen very fast while write is done with a lock.

Q) Difference between fail-fast Iterator and fail-safe Iterator in Java?
Fail fast iterator throws ConcurrentModificationException if there is any structural modification done while iterating it. While fail safe iterator doesn't throw ConcurrentModificationException, because it makes a copy of the internal data structure (object array) and iterates over the copied data structure. So any structural modification done to the iterator affects the copied data structure.
Q) What is Concurrent Modification in Java Collection?
When one or more thread is iterating over the collection, in between one thread changes the structure of the collection (either adding the element to the collection or by deleting the element in the collection or by updating the value at particular position in the collection) is known as Concurrent Modification.
Q) What is ConcurrentModificationException?
Java Collection classes are fail-fast which means that if the Collection will be changed while some thread is traversing over it using iterator, the will throw a java.util.ConcurrentModificationException.
Q) What is race condition in java multi threading?

A race condition may occurs when two or more threads can monitor the same shared data and they try to change it at the same time.


System.out.println(totalAmount); // prints 1000
if(interestAmount == 10){
   totalAmount += totalAmount*interestAmount/100;   
   // If another thread change the interestAmount to 5 in between. totalAmount will be 1050 
System.out.println(totalAmount); //we are expecting totalAmount 1100 here but it prints 1050   
Solution: In order to prevent race conditions from occurring, we would typically put a lock around the shared data to ensure only one thread can access the data at a time.
// Obtain lock here for interestAmount
if(interestAmount == 10){
   totalAmount += totalAmount*interestAmount/100;   
//Release lock here for interestAmount
Q) Difference between Static binding and Dynamic binding in java ?

1.Static binding in Java occurs during compile time while dynamic binding occurs during runtime.

2.Static binding uses type(Class) information for binding while dynamic binding uses instance of class(Object) to resolve calling of method at run-time.

3.Overloaded methods are bonded using static binding while overridden methods are bonded using dynamic binding at runtime.

Q) Difference between stack memory and heap memory in Java?

Stack memory is used to store local variables and function call, while heap memory is used to store objects in Java.

Heap memory is also called as shared memory as this is the place where multiple threads will share the same data, while stacks are only visible to the owner Thread.

If there is no memory left in stack for storing function call or local variable, JVM will throw java.lang.StackOverFlowError while if there is no more heap space for creating object, JVM will throw java.lang.OutOfMemoryError.

Java -Xms<size> // set initial Java heap size

Java -Xmx<size> // set maximum Java heap size

Java -Xss<size> // set java thread stack size

Q) Difference between class and object?
Class is blueprint to create objects, means you can create different object based on one class which varies in there property. e.g. if Car is a class than Mercedes, BMW or Audi can be considered as object because they are essentially a car but have different size, shape, color and feature.
Q) What if we call run() method directly instead start() method?
If you call the run() method directly it will run the code on the current thread, not on a new thread. Because each thread starts in a separate call stack, which you will get after invoking start() method.
Q) What is deadlock in java?

Deadlock describes a situation where two or more threads are blocked forever, waiting for each other. Deadlocks can occur in Java because the synchronized keyword causes the executing thread to block while waiting for the lock, or monitor, associated with the specified object.Since the thread might already hold locks associated with other objects, two threads could each be waiting for the other to release a lock; in such a case, they will end up waiting forever.

Deadlock Example
Q) Difference between extending Thread class and implementing Runnable interface?

1. Inheritance Option : The limitation with "extends Thread" approach is that if you extend Thread, you can not extend anything else . Java does not support multiple inheritance. In reality , you do not need Thread class behaviour , because in order to use a thread you need to instantiate one anyway. On the other hand, Implementing the Runnable interface gives you the choice to extend any class you like , but still define behaviour that will be run by separate thread.

2. Re-usability : In "implements Runnable" , we are creating a different Runnable class for a specific behaviour job (if the work you want to be done is job). It gives us the freedom to reuse the specific behaviour job whenever required. "extends Thread" contains both thread and job specific behaviour code. Hence once thread completes execution , it can not be restart again.

3. Object Oriented Design : Implementing Runnable should be preferred . It does not specializing or modifying the thread behaviour . You are giving thread something to run. We conclude that Composition is the better way. Composition means two objects A and B satisfies has-a relationship. "extends Thread" is not a good Object Oriented practice.

4. Loosely-coupled : "implements Runnable" makes the code loosely-coupled and easier to read . Because the code is split into two classes . Thread class for the thread specific code and your Runnable implementation class for your job that should be run by a thread code. "extends Thread" makes the code tightly coupled . Single class contains the thread code as well as the job that needs to be done by the thread.

5. Functions overhead : "extends Thread" means inheriting all the functions of the Thread class which we may do not need . job can be done easily by Runnable without the Thread class functions overhead.

Q) What's the difference between StackOverflowError and OutOfMemoryError?

When you start JVM you define how much RAM it can use use for processing. JVM divides this into certain memory locations for its processing purpose, two of those are Stack & Heap. OutOfMemoryError is related to Heap, while StackOverflowError is related to Stack.

If there is no more heap space for creating object, JVM will throw java.lang.OutOfMemoryError, while if there is no memory left in stack for storing function call or local variable, JVM will throw java.lang.StackOverFlowError.

Q) Class level locking vs Object level locking

Class level locking prevents multiple threads to enter in synchronized block in any of all available instances on runtime. This means if in runtime there are 100 instances of a class then only one thread will be able to execute it in any one of instance at a time, and all other instances will be locked for other threads.

Object level locking is mechanism when you want to synchronize a non-static method or non-static code block such that only one thread will be able to execute the code block on given instance of the class.

Q) What is the best approach to store password in Java?
Both char array or String can be used to store text,But char array is preferred over String.

Here is why:

1. Strings are immutable in Java so if you store password as plain text it will be available in memory until Garbage collector clears it and since String uses String pool for reusability so there is high risk of your text data remaining in memory for long duration. Access to memory dump can disclose the password in clear text and now we got one reason to have the passwords in encrypted form.
2. String literals or String objects created by using new String("") can be shown directly as plain text on console. But char array can display only unsigned hexadecimal representation of the hash code of the array reference.e.g:- [I@1db9742

Publish Your Article

Receive Latest Java Examples in Your Email: