Most Important Java Interview Questions And Answers

Most Important Java Interview Questions And Answers For Freshers and Experienced Candidate in 2021: In this Article, we have provided 200+ important and Most asked Java Interview Questions with their answers. These Java Interview Questions are generally asked in the technical round of Java Interviews.

Difference between Procedure Oriented and object oriented programming language?

Procedure Oriented object oriented
Divided into In POP program is divided
into small parts called
In OOP program is divided
into parts called objects.
Importance In POP importance is not
given to data but to
function as well as
sequence of actions to be
In OOP importance is given
to the data rather than
procedures or functions
because it works as a real
Approach POP follows TOP Down
OOP follows Bottom UP
Access Specifier POP does not have any
access specifier.
OOP has access specifier
named public, private,
protected etc
Data Moving In POP data can move
freely from function to
function in the system
In OOP object can move
and communicate with
each other through
member functions.
Expansion To add new data and
function in POP is not so
OOP provides an easy way
to add new data and

What are the principle concepts of OOPS?
There are four principle concepts upon which object oriented design and programming
rest. They are:
 Abstraction
 Polymorphism
 Inheritance
 Encapsulation
(i.e. easily remembered as A-PIE).

What is Abstraction?
Abstraction refers to the act of representing essential features without including the
background details or explanations.

What is Encapsulation?
Encapsulation is a technique used for hiding the properties and behaviors of an object and
allowing outside access only as appropriate. It prevents other objects from directly altering
or accessing the properties or methods of the encapsulated object.

What is the difference between abstraction and encapsulation?
Abstraction focuses on the outside view of an object (i.e. the interface) Encapsulation
(information hiding) prevents clients from seeing it’s inside view, where the behavior of
the abstraction is implemented.
Abstraction solves the problem in the design side while Encapsulation is the
Encapsulation is the deliverables of Abstraction. Encapsulation barely talks about grouping
up your abstraction to suit the developer needs.

What is Inheritance?
Inheritance is the process by which objects of one class acquire the properties of objects of
another class.
A class that is inherited is called a superclass.
The class that does the inheriting is called a subclass.
Inheritance is done by using the keyword extends.
The two most common reasons to use inheritance are:
To promote code reuse
To use polymorphism

What is Polymorphism?
Polymorphism is briefly described as “one interface, many implementations.”
Polymorphism is a characteristic of being able to assign a different meaning or usage to
something in different contexts – specifically, to allow an entity such as a variable, a
function, or an object to have more than one form.

How does Java implement polymorphism?
(Inheritance, Overloading and Overriding are used to achieve Polymorphism in java).
Polymorphism manifests itself in Java in the form of multiple methods having the same
In some cases, multiple methods have the same name, but different formal argument lists
(overloaded methods).
In other cases, multiple methods have the same name, same return type, and same formal
argument list (overridden methods).

Explain the different forms of Polymorphism.
There are two types of polymorphism one is Compile time polymorphism and the other is
run time polymorphism. Compile time polymorphism is method overloading. Runtime time
polymorphism is done using inheritance and interface.
From a practical programming viewpoint, polymorphism manifests itself in three distinct
forms in Java:
Method overloading
Method overriding through inheritance
Method overriding through the Java interface
What is runtime polymorphism or dynamic method dispatch?
In Java, runtime polymorphism or dynamic method dispatch is a process in which a call to
an overridden method is resolved at runtime rather than at compile-time. In this process,
an overridden method is called through the reference variable of a superclass. The
determination of the method to be called is based on the object being referred to by the
reference variable.

What is Dynamic Binding?
Binding refers to the linking of a procedure call to the code to be executed in response to
the call. Dynamic binding (also known as late binding) means that the code associated with
a given procedure call is not known until the time of the call at run-time. It is associated
with polymorphism and inheritance.

What is method overloading?
Method Overloading means to have two or more methods with same name in the same
class with different arguments. The benefit of method overloading is that it allows you to
implement methods that support the same semantic operation but differ by argument
number or type.
Overloaded methods MUST change the argument list
Overloaded methods CAN change the return type
Overloaded methods CAN change the access modifier
Overloaded methods CAN declare new or broader checked exceptions
A method can be overloaded in the same class or in a subclass

What is method overriding?
Method overriding occurs when sub class declares a method that has the same type
arguments as a method declared by one of its superclass. The key benefit of overriding is
the ability to define behavior that’s specific to a particular subclass type.
The overriding method cannot have a more restrictive access modifier than the method
being overridden (Ex: You can’t override a method marked public and make it protected).
You cannot override a method marked final
You cannot override a method marked static

What is a class?
 A class is a specification or blue print or template of an object.
 Class is a logical construct; an object has physical reality.
 Class is a structure
 Binding the data with its related and corresponding functions.
 Class is the base for encapsulation.
 Class is a user defined data type in java.
 Class will act as the base for encapsulation and implement the concept of
encapsulation through objects.
 Any java applications look like collection of classes but whereas c- application looks
like collection of functions.
 Class contains variables and methods.

What is an object ?
 Object is nothing but instance (dynamic memory allocation) of a class.
 The dynamic memory allocated at run time for the members [non-static variables] of the class is known as object.
 Object is an encapsulated form of all non-static variables and non-static methods of
a particular class.
 The process of creating objects out of class is known as instantiation.

What are the Object Characteristics?
The three key characteristics of Object are
 State
 Behaviour
 Identity
 Instance variables value is called object state.
 An object state will be changed if instance variables value is changed.
 Behaviour of an object is defined by instance methods.
 Behaviour of an object is depends on the messages passed to it.
 So an object behaviour depends on the instance methods.
 Identity is the hash code of an object, it is a 32-bit integer number created randomly
and assigned to an object by default by JVM.
 Developer can also generate hash code of an object based on the state of that object
by overriding hashcode() method of java.lang.Object class.
Then if state is changed, automatically hashcode will be changed.

What Object Contains?
 Object of any class contains only data.
 Apart from the data object of a class would not contains anything else.
 Object of a class would not contain any functionalities or logic.
 Thus object of a class would be representing only data and not represent logic.

What is state of the Object?
The data present inside object of a class at that point of time is known as state of the

What is behaviour of the object?
The functionalities associated with the object => Behaviour of the object.
The state of the object changes from time-to-time depending up on the functionalities that
are executed on that object but whereas behaviour of the object would not change.

In how many ways can you create an object in Java?
There are four ways of creating objects in Java:
1. Using new operator
Employee obj = new Employee ();
Here, we are creating Employee class object ‘obj’ using new operator.
2. Using factory methods:
Number Format obj = NumberFormat. getNumberInstance( );
Here, we are creating NumberFormat object using the factory method getNumberInstance(
3. Using newInstance( ) method. Here we should follow two steps, as:
(a) First, store the class name ‘Employee’ as a string into an object. For this purpose, factory
metod forName( ) of the class ‘Class’ will be useful:
Class c = Class.forName(“Employee”);
We should note that there is a class with the name ‘Class’ in java.lang package.
(b) Next, create another object to the class whose name is in the object c. For this purpose ,
we need newInstance( ) method of the class ‘Class’ as:
Employee obj = ( Employee)c.newInstance( );
4. By cloning an already available object, we can create another object. Creating
exact copy of an existing object is called ‘cloning’.
Employee obj1 = new Employee ( );
Employee obj2 = (Employee)obj1.clone( );
Earlier, we created obj2 by cloning the Employee object obj1.clone( ) method of Object
class is used to clone object.We should note that there is a class by the name ‘Object’ in
java.lang package.

Define 5 different places to define Object of a class in java?
Object of a class can be defined at 5 different places.
1. Defining object of a class as local to a method or local variable.
2. Defining object of a class as an instance variable of another class.
3. Defining object of a class as the parameter of the method.
4. Defining object of a class as the return data type of the method.
5. Defining object of a class as the static variable or class variable of another class.

What is a Reference variable?
Reference variable is a variable which would be representing the address of the object.
Reference will act as a pointer and handler to the object.
Since reference variable always points an object.
In practice we call the reference variable also as an object.
We can create an object by using new operator.
If we want to call any method inside the class we need object
Syntax: A obj= new A();

What is object graph?
Object graph is a graph showing relationship between different objects in memory.

Explain what can we use primitive data types as objects?
Primitive data types like int can be handled as objects by the use of their respective
wrapper classes. For example, Integer is a wrapper class for primitive data type int. We can
apply different methods to a wrapper class, just like any other object.

What is mutable object and immutable object?
If an object value is changeable then we can call it as Mutable object. (Ex., StringBuffer, …) If
you are not allowed to change the value of an object, it is immutable object. (Ex., String,
Integer, Float, …)

How many objects are created in the following piece of code?
MyClass c1, c2, c3;
c1 = new MyClass ();
c3 = new MyClass ();
Only 2 objects are created, c1 and c3. The reference c2 is only declared and not initialized.

Explain what objects are stored in Java?
In java, each object when created gets a memory space from a heap. When an object is
destroyed by a garbage collector, the space allocated to it from the heap is re-allocated to
the heap and becomes available for any new objects.

Explain what can we find the actual size of an object on the heap?
In java, there is no way to find out the exact size of an object of the heap.

Which of the following classes will have more memory allocated?
Class A: Three methods, four variables, no object
Class B: Five methods, three variables, no object
Answer: –
Memory isn’t allocated before creation of objects. Since for both classes, there are no
objects created so no memory is allocated on heap for any class.

What is memory leak?
A memory leak is where an unreferenced object that will never be used again still hangs
around in memory and doesn’t get garbage collected.

I want my class to be developed in such a way that no other class (even derived class)
can create its objects. Explain what can I do so?
If we declare the constructor of a class as private, it will not be accessible by any other class
and hence, no other class will be able to instantiate it and formation of its object will be
limited to itself only.

What are the Object and Class classes used for? Which class should you use to obtain
design information about an object?
Differentiate between a Class and an Object?
The Object class is the highest-level class in the Java class hierarchy. The Class class is used
to represent the classes and interfaces that are loaded by a Java program. The Class class is
used to obtain information about an object’s design. A Class is only a definition or
prototype of real life object. Whereas an object is an instance or living representation of
real life object. Every object belongs to a class and every class contains one or more related

What is the difference between an object and an instance?
An Object May not have a class definition. eg int a[] where a is an array.
An Instance should have a class definition.
eg MyClass my=new MyClass();
my is an instance.

What is the difference between instance, object, reference and a class?
Class: A class is a user defined data type with set of data members & member functions
Object: An Object is an instance of a class
Reference: A reference is just like a pointer pointing to an object
Instance: This represents the values of data members of a class at a particular time

What is a singleton class?
What is singleton pattern?
This design pattern is used by an application to ensure that at any time there is only one
instance of a class created. You can achieve this by having the private constructor in the
class and having a getter method which returns an object of the class and creates one for
the first time if its null.

What is the purpose of the System class?
The purpose of the System class is to provide access to system resources.

What is the purpose of the Runtime class?
The purpose of the Runtime class is to provide access to the Java runtime system.
It returns the runtime information like memory availability.
* Runtime.freeMemory() –> Returns JVM Free Memory
* Runtime.maxMemory() –> Returns the maximum amount of memory that the
JVM will attempt to use.
* Runtime.gc() –> It also helps to run the garbage collector

What would happen if you say this = null?
It will come up with Error Message
“The left-hand side of an assignment must be a variable”.

What are the differences between method overloading and method overriding?

Overloaded Method Overridden Method
Arguments Must change Must not change
Return type Can change Can’t change except for covariant returns
Exceptions Can change Can reduce or eliminate. Must not throw
new or broader checked exceptions
Access Can change Must not make more restrictive

Can overloaded methods be override too?
Yes, derived classes still can override the overloaded methods. Polymorphism can still
happen. Compiler will not binding the method calls since it is overloaded, because it might
be overridden now or in the future.

Is it possible to override the main method?
NO, because main is a static method. A static method can’t be overridden in Java.

How to invoke a superclass version of an Overridden method?
To invoke a superclass method that has been overridden in a subclass, you must either call
the method directly through a superclass instance, or use the super prefix in the subclass
itself. From the point of the view of the subclass, the super prefix provides an explicit
reference to the superclass’ implementation of the method.
// From subclass

What is super?
super is a keyword which is used to access the method or member variables from the
superclass. If a method hides one of the member variables in its superclass, the method can
refer to the hidden variable through the use of the super keyword. In the same way, if a
method overrides one of the methods in its superclass, the method can invoke the
overridden method through the use of the super keyword.
You can only go back one level.
In the constructor, if you use super(), it must be the very first code, and you cannot access
any variables or methods to compute its parameters.

How do you prevent a method from being overridden?
To prevent a specific method from being overridden in a subclass, use the final modifier on
the method declaration, which means “this is the final implementation of this method”, the
end of its inheritance hierarchy.
public final void exampleMethod() {
// Method statements

What is an Interface?
An interface is a description of a set of methods that conforming implementing classes
must have.
You can’t mark an interface as final.
Interface variables must be static.
An Interface cannot extend anything but another interfaces.

Can we instantiate an interface?
You can’t instantiate an interface directly, but you can instantiate a class that implements
an interface.

Can we create an object for an interface?
Yes, it is always necessary to create an object implementation for an interface. Interfaces
cannot be instantiated in their own right, so you must write a class that implements the
interface and fulfill all the methods defined in it.

Do interfaces have member variables?
Interfaces may have member variables, but these are implicitly public, static, and final- in
other words, interfaces can declare only constants, not instance variables that are available
to all implementations and may be used as key references for method arguments for

What modifiers are allowed for methods in an Interface?
Only public and abstract modifiers are allowed for methods in interfaces.

What is a marker interface?
Marker interfaces are those which do not declare any required methods, but signify their
compatibility with certain operations. The interface and Cloneable are
typical marker interfaces. These do not contain any methods, but classes must implement
this interface in order to be serialized and de-serialized.

What is an abstract class?
Abstract classes are classes that contain one or more abstract methods. An abstract method
is a method that is declared, but contains no implementation.
If even a single method is abstract, the whole class must be declared abstract.
Abstract classes may not be instantiated, and require subclasses to provide
implementations for the abstract methods.
You can’t mark a class as both abstract and final.

Can we instantiate an abstract class?
An abstract class can never be instantiated. Its sole purpose is to be extended (subclassed).

When should I use abstract classes and when should I use interfaces?
Use Interfaces when…
You see that something in your design will change frequently.
If various implementations only share method signatures then it is better to use Interfaces.
you need some classes to use some methods which you don’t want to be included in the
class, then you go for the interface, which makes it easy to just implement and make use of
the methods defined in the interface.

Use Abstract Class when…
If various implementations are of the same kind and use common behavior or status then
abstract class is better to use.
When you want to provide a generalized form of abstraction and leave the implementation
task with the inheriting subclass.
Abstract classes are an excellent way to create planned inheritance hierarchies. They’re
also a good choice for nonleaf classes in class hierarchies.

When you declare a method as abstract, can other non abstract methods access it?
Yes, other non abstract methods can access a method that you declare as abstract.

Can there be an abstract class with no abstract methods in it?
Yes, there can be an abstract class without abstract methods.

What is Constructor?
A constructor is a special method whose task is to initialize the object of its class.
It is special because its name is the same as the class name.
They do not have return types, not even void and therefore they cannot return values.
They cannot be inherited, though a derived class can call the base class constructor.
Constructor is invoked whenever an object of its associated class is created.

How does the Java default constructor be provided?
If a class defined by the code does not have any constructor, compiler will automatically
provide one no-parameter-constructor (default-constructor) for the class in the byte code.
The access modifier (public/private/etc.) of the default constructor is the same as the class

Can constructor be inherited?
No, constructor cannot be inherited, though a derived class can call the base class

What are the differences between Contructors and Methods?

Constructors Methods
Purpose Create an instance of a class Group Java statements
Modifiers Cannot be abstract, final, static, or synchronized Can be abstract, final, static, or synchronized
Return Type No return type, not even void void or a valid return type
Name Same name as the class Any name except the class.
Inheritance Constructors are not inherited Methods are inherited

 Refers to another constructor in the same class. If used, it must be the first line of
the constructor
 Refers to an instance of the owning class. Cannot be used by static methods.
 Super Calls the constructor of the parent class. If used, must be the first line of the
constructor Calls an overridden method in the parent class.

How are this() and super() used with constructors?
Constructors use this to refer to another constructor in the same class with a different
parameter list.
Constructors use super to invoke the superclass’s constructor. If a constructor uses super,
it must use it in the first line; otherwise, the compiler will complain.

What are the differences between Class Methods and Instance Methods?
 Class Methods
 Instance Methods
a) Class methods are methods which are declared as static. The method can be called
without creating an instance of the class Instance methods on the other hand
require an instance of the class to exist before they can be called, so an instance of a
class needs to be created by using the new keyword.
Instance methods operate on specific instances of classes.
b) Class methods can only operate on class members and not on instance members as
class methods are unaware of instance members.Instance methods of the class can
also not be called from within a class method unless they are being called on an
instance of that class.
c) Class methods are methods which are declared as static. The method can be called
without creating an instance of the class. Instance methods are not declared as

How are this() and super() used with constructors?
Constructors use this to refer to another constructor in the same class with a different
parameter list.
Constructors use super to invoke the superclass’s constructor. If a constructor uses super,
it must use it in the first line; otherwise, the compiler will complain.

What are Access Specifiers?
One of the techniques in object-oriented programming is encapsulation. It concerns the
hiding of data in a class and making this class available only through methods. Java allows
you to control access to classes, methods, and fields via so-called access specifiers..

What are Access Specifiers available in Java?
Java offers four access specifiers, listed below in decreasing accessibility:
Public- public classes, methods, and fields can be accessed from everywhere.
Protected- protected methods and fields can only be accessed within the same class to
which the methods and fields belong, within its subclasses, and within classes of the same
Default(no specifier)- If you do not set access to specific level, then such a class, method, or
field will be accessible from inside the same package to which the class, method, or field
belongs, but not from outside this package.
Private- private methods and fields can only be accessed within the same class to which the
methods and fields belong. private methods and fields are not visible within subclasses and
are not inherited by subclasses.

What is final modifier?
The final modifier keyword makes that the programmer cannot change the value anymore.
The actual meaning depends on whether it is applied to a class, a variable, or a method.
final Classes- A final class cannot have subclasses.
final Variables- A final variable cannot be changed once it is initialized.
final Methods- A final method cannot be overridden by subclasses.

What are the uses of final method?
There are two reasons for marking a method as final:
Disallowing subclasses to change the meaning of the method.
Increasing efficiency by allowing the compiler to turn calls to the method into inline Java

What is static block?
Static block which exactly executed exactly once when the class is first loaded into JVM.
Before going to the main method the static block will execute.

What are static variables?
Variables that have only one copy per class are known as static variables. They are not
attached to a particular instance of a class but rather belong to a class as a whole. They are
declared by using the static keyword as a modifier.
static type varIdentifier;
where, the name of the variable is varIdentifier and its data type is specified by type.
Note: Static variables that are not explicitly initialized in the code are automatically
initialized with a default value. The default value depends on the data type of the variables.

What is the difference between static and non-static variables?
A static variable is associated with the class as a whole rather than with specific instances
of a class. Non-static variables take on unique values with each object instance.

What are static methods?
Methods declared with the keyword static as modifier are called static methods or class
methods. They are so called because they affect a class as a whole, not a particular instance
of the class. Static methods are always invoked without reference to a particular instance of
a class.
Note:The use of a static method suffers from the following restrictions:
A static method can only call other static methods.
A static method must only access static data.
A static method cannot reference to the current object using keywords super or this.

What is an Iterator ?
The Iterator interface is used to step through the elements of a Collection.
Iterators let you process each element of a Collection.
Iterators are a generic way to go through all the elements of a Collection no matter how it is
Iterator is an Interface implemented a different way for every Collection.

How do you traverse through a collection using its Iterator?
To use an iterator to traverse through the contents of a collection, follow these steps:
Obtain an iterator to the start of the collection by calling the collection’s iterator()
Set up a loop that makes a call to hasNext(). Have the loop iterate as long as hasNext()
returns true.
Within the loop, obtain each element by calling next().

How do you remove elements during Iteration?
Iterator also has a method remove() when remove is called, the current element in the
iteration is deleted.

What is the difference between Enumeration and Iterator?
Enumeration                                                             Iterator
Enumeration doesn’t have a remove() method                      Iterator has a remove() method

Enumeration acts as Read-only interface,                              Can be abstract, final, native,
because it has the methods only to traverse                          static, or synchronized
and fetch the objects

Note: So Enumeration is used whenever we want to make Collection objects as Read-only.

How is ListIterator?
ListIterator is just like Iterator, except it allows us to access the collection in either the
forward or backward direction and lets us modify an element

What is the List interface?
The List interface provides support for ordered collections of objects.
Lists may contain duplicate elements.

What are the main implementations of the List interface ?
The main implementations of the List interface are as follows :
ArrayList : Resizable-array implementation of the List interface. The best all-around
implementation of the List interface.
Vector : Synchronized resizable-array implementation of the List interface with additional
“legacy methods.”
LinkedList : Doubly-linked list implementation of the List interface. May provide better
performance than the ArrayList implementation if elements are frequently inserted or
deleted within the list. Useful for queues and double-ended queues (deques).

What are the advantages of ArrayList over arrays ?
Some of the advantages ArrayList has over arrays are:
 It can grow dynamically
 It provides more powerful insertion and search mechanisms than arrays.

Difference between ArrayList and Vector ?
      ArrayList                                                           Vector
a) ArrayList is NOT synchronized by default.         Vector List is synchronized by default.
b) ArrayList can use only Iterator to access           Vector list can use Iterator and the elements                                      the elements.                                                     Enumeration Interface to access the elements.
c) The ArrayList increases its array size by             A Vector defaults to doubling the size
size 50 percent if it runs out of room.                of its array if it runs out of room
d) ArrayList has no default size.                             While vector has a default size-10

How to obtain Array from an ArrayList ?
Array can be obtained from an ArrayList using toArray() method on ArrayList.
List arrayList = new ArrayList();
Object a[] = arrayList.toArray();

Why insertion and deletion in ArrayList is slow compared to LinkedList ?
ArrayList internally uses and array to store the elements, when that array gets filled by
inserting elements a new array of roughly 1.5 times the size of the original array is created
and all the data of old array is copied to new array.
During deletion, all elements present in the array after the deleted elements have to be
moved one step back to fill the space created by deletion. In linked list data is stored in
nodes that have reference to the previous node and the next node so adding element is
simple as creating the node an updating the next pointer on the last node and the previous
pointer on the new node. Deletion in linked list is fast because it involves only updating the
next pointer in the node before the deleted node and updating the previous pointer in the
node after the deleted node.

Why are Iterators returned by ArrayList called Fail Fast ?
Because, if list is structurally modified at any time after the iterator is created, in any way
except through the iterator’s own remove or add methods, the iterator will throw a
ConcurrentModificationException. Thus, in the face of concurrent modification, the iterator
fails quickly and cleanly, rather than risking arbitrary, non-deterministic behavior at an
undetermined time in the future.

How do you decide when to use ArrayList and When to use LinkedList?
If you need to support random access, without inserting or removing elements from any
place other than the end, then ArrayList offers the optimal collection. If, however, you need
to frequently add and remove elements from the middle of the list and only access the list
elements sequentially, then LinkedList offers the better implementation.

What is the Set interface ?
The Set interface provides methods for accessing the elements of a finite mathematical set
Sets do not allow duplicate elements Contains no methods other than those inherited from
Collection It adds the restriction that duplicate elements are prohibited Two Set objects are
equal if they contain the same elements

What are the main Implementations of the Set interface ?
The main implementations of the List interface are as follows:

What is a HashSet ?
A HashSet is an unsorted, unordered Set.
It uses the hashcode of the object being inserted (so the more efficient your hashcode()
implementation the better access performance you’ll get).
Use this class when you want a collection with no duplicates and you don’t care about
order when you iterate through it.

What is a TreeSet ?
TreeSet is a Set implementation that keeps the elements in sorted order. The elements are
sorted according to the natural order of elements or by the comparator provided at
creation time.

What is an EnumSet ?
An EnumSet is a specialized set for use with enum types, all of the elements in the EnumSet
type that is specified, explicitly or implicitly, when the set is created.

Difference between HashSet and TreeSet ?
HashSet                                                              TreeSet
1.   HashSet is under set interface i.e.                            TreeSet is under set i.e. it provides
it does not guarantee for either sorted                    elements in a sorted order
order or sequence order.

2.  We can add any type of elements to hash set.         We can add only similar types of
elements to tree set.

What is a Map ?
A map is an object that stores associations between keys and values (key/value pairs).
Given a key, you can find its value. Both keys and values are objects.
The keys must be unique, but the values may be duplicated.
Some maps can accept a null key and null values, others cannot.

What are the main Implementations of the Map interface ?
The main implementations of the List interface are as follows:

What is a TreeMap ?
TreeMap actually implements the SortedMap interface which extends the Map interface. In
a TreeMap the data will be sorted in ascending order of keys according to the natural order
for the key’s class, or by the comparator provided at creation time. TreeMap is based on the
Red-Black tree data structure.

How do you decide when to use HashMap and when to use TreeMap ?
For inserting, deleting, and locating elements in a Map, the HashMap offers the best
alternative. If, however, you need to traverse the keys in a sorted order, then TreeMap is
your better alternative. Depending upon the size of your collection, it may be faster to add
elements to a HashMap, then convert the map to a TreeMap for sorted key traversal.

How does a Hashtable internally maintain the key-value pairs?
TreeMap actually implements the SortedMap interface which extends the Map interface. In
a TreeMap the data will be sorted in ascending order of keys according to the natural order
for the key’s class, or by the comparator provided at creation time. TreeMap is based on the
Red-Black tree data structure.

What Are the different Collection Views That Maps Provide?
Maps Provide Three Collection Views.
Key Set – allow a map’s contents to be viewed as a set of keys.
Values Collection – allow a map’s contents to be viewed as a set of values.
Entry Set – allow a map’s contents to be viewed as a set of key-value mappings.

What is a KeySet View ?
KeySet is a set returned by the keySet() method of the Map Interface, It is a set that
contains all the keys present in the Map.

What is a Values Collection View ?
Values Collection View is a collection returned by the values() method of the Map Interface,
It contains all the objects present as values in the map.

What is an EntrySet View ?
Entry Set view is a set that is returned by the entrySet() method in the map and contains
Objects of type Map. Entry each of which has both Key and Value.

How do you sort an ArrayList (or any list) of user-defined objects ?
Create an implementation of the java.lang.Comparable interface that knows how to order
your objects and pass it to java.util.Collections.sort(List, Comparator).

What is the Comparable interface?

The Comparable interface is used to sort collections and arrays of objects using the
Collections.sort() and java.utils.Arrays.sort() methods respectively. The objects of the class
implementing the Comparable interface can be ordered.

The Comparable interface in the generic form is written as follows:

interface Comparable <T>

where T is the name of the type parameter.

All classes implementing the Comparable interface must implement the compareTo()
method that has the return type as an integer. The signature of the compareTo() method is
as follows:

int i = object1.compareTo(object2)

If object1 < object2: The value of i returned will be negative.

If object1 > object2: The value of i returned will be positive.

If object1 = object2: The value of i returned will be zero.

What are the differences between the Comparable and Comparator interfaces?

             Comparable             Comparato
It uses the compareTo() method.
int objectOne.compareTo(objectTwo)
It uses the compare() method.
int compare(ObjOne, ObjTwo)
It is necessary to modify the class whose
instance is going to be sorted.
A separate class can be created in order to
sort the instances..
Only one sort sequence can be created.
It is frequently used by the API classes.
Many sort sequences can be created.
It is frequently used by the API classes.

What is a Thread?
In Java, “thread” means two different things:
 An instance of class java.lang.Thread.
 A thread of execution.
An instance of Thread is just…an object. Like any other object in Java, it has variables and
methods, and lives and dies on the heap. But a thread of execution is an individual process
(a “lightweight” process) that has its own call stack. In Java, there is one thread per call
stack—or, to think of it in reverse, one call stack per thread. Even if you don’t create any
new threads in your program, threads are back there running.

The main() method, that starts the whole ball rolling, runs in one thread, called
(surprisingly) the main thread. If you looked at the main call stack (and you can, any time
you get a stack trace from something that happens after main begins, but not within
another thread), you’d see that main() is the first method on the stack— the method at the
bottom. But as soon as you create a new thread, a new stack materializes and methods
called from that thread run in a call stack that’s separate from the main() call stack.

What is the difference between thread and process?

Differences between threads and processes are:-
1. Threads share the address space of the process that created it; processes have their own
2. Threads have direct access to the data segment of its process; processes have their own
copy of the data segment of the parent process.
3. Threads can directly communicate with other threads of its process; processes must use
inter-process communication to communicate with sibling processes.
4. Threads have almost no overhead; processes have considerable overhead.
5. New threads are easily created; new processes require duplication of the parent process.
6. Threads can exercise considerable control over threads of the same process; processes
can only exercise control over child processes.
7. Changes to the main thread (cancellation, priority change, etc.) may affect the behavior of
the other threads of the process; changes to the parent process do not affect child

What are the advantages or usage of threads?
Threads support concurrent operations. For example,
• Multiple requests by a client on a server can be handled as an individual client thread.
• Long computations or high-latency disk and network operations can be handled in the
background without disturbing foreground computations or screen updates.
Threads often result in simpler programs.
• In sequential programming, updating multiple displays normally requires a big whileloop that performs small parts of each display update. Unfortunately, this loop basically
simulates an operating system scheduler. In Java, each view can be assigned a thread to
provide continuous updates.
• Programs that need to respond to user-initiated events can set up service routines to
handle the events without having to insert code in the main routine to look for these
Threaded applications exploit parallelism.
• A computer with multiple CPUs can literally execute multiple threads on different
functional units without having to simulating multi-tasking (“time sharing”).
• On some computers, one CPU handles the display while another handles computations or
database accesses, thus, providing extremely fast user interface response times.

What is the use of synchronized keywords?
The synchronized keywords can be applied to static/non-static methods or a block of code. Only
one thread at a time can access synchronized methods and if there are multiple threads
trying to access the same method then other threads have to wait for the execution of
the method by one thread. Synchronized keyword provides a lock on the object and thus
prevents race condition. E.g.
public void synchronized method(){}
public void synchronized staticmethod(){}
public void myMethod(){
synchronized (this){ // synchronized keyword on block of code

What is a volatile keyword?
In general, each thread has its own copy of the variable, such that one thread is not concerned
with the value of the same variable in the other thread. But sometimes this may not be the case.
Consider a scenario in which the count variable is holding the number of times a method is
called for a given class irrespective of any thread calling, in this case, irrespective of thread
access the count has to be increased so the count variable is declared as volatile. The copy
of the volatile variable is stored in the main memory, so every time a thread access the variable even for reading purpose the local copy is updated each time from the main memory.
The volatile variable also has performance issues.

What is the difference between yield() and sleep()?
yield() allows the current thread to release its lock from the object and the scheduler gives the
lock of the object to the other thread with the same priority.
sleep() allows the thread to go to sleep state for x milliseconds. When a thread goes
into a sleep state it doesn’t release the lock.

What is the difference between wait() and sleep()?
- wait() is a method of Object class. sleep() is a method of Object class.
- sleep() allows the thread to go to sleep state for x milliseconds. When a thread goes into
sleep state it doesn’t release the lock. wait() allows thread to release the lock and goes to
suspended state. The thread is only active when a notify() or notifAll() method is called for
the same object.

What is difference between notify() and notfiyAll()?
notify( ) wakes up the first thread that called wait( ) on the same object.
notifyAll( ) wakes up all the threads that called wait( ) on the same object. The
highest priority thread will run first.

What happens if a start method is not invoked and the run method is directly
If a thread has been instantiated but not started it is said to be in new state. Unless until a
start() method is invoked on the instance of the thread, it will not said to be alive. If you do
not call a start() method on the newly created thread instance thread is not considered to
be alive. If the start() method is not invoked and the run() method is directly called on the
Thread instance, the code inside the run() method will not run in a separate new thread but
it will start running in the existing thread.

What happens when start() is called?
A new thread of execution with a new call stack starts. The state of thread changes from
new to runnable. When the thread gets chance to execute its target run() method starts to

If code running is a thread creates a new thread what will be the initial priority of the
newly created thread?
When a code running in a thread creates a new thread object , the priority of the new
thread is set equal to the priority of the thread which has created it.

What are the daemon threads?
Daemon thread are service provider threads run in the background, these not used to run
the application code generally. When all user threads (non-daemon threads) complete their
execution, the jvm exit the application whatever may be the state of the daemon threads.
Jvm does not wait for the daemon threads to complete their execution if all user threads
have completed their execution.

How many locks does an object have?
Each object has only one lock.

Why would you use a synchronized block vs. synchronized method?
Synchronized blocks place locks for shorter periods than synchronized methods.

There are two classes: A and B. The class B need to inform a class A when some
important event has happened. What Java technique would you use to implement it?
If these classes are threads I’d consider notify() or notifyAll(). For regular classes you can
use the Observer interface.

How do you ensure that N thread can access N resources without deadlock?
Key point here is order, if you acquire resources in a particular order and release resources
in reverse order you can prevent deadlock.

What is the difference between Composition and Inheritance in OOP?
One of the good question to check the candidate’s object-oriented programming skills.
There are several differences between Composition and Inheritance in Java, some of them
are following:
1. The Composition is more flexible because you can change the implementation at
runtime by calling setXXX() method, but Inheritance cannot be changed i.e. you cannot
ask a class to implement another class at runtime.
2. Composition builds HAS-A relationship while Inheritance builds IS-A relationship e.g. A
Room HAS A Fan, but Mango IS-A Fruit.
3. The parent-child relationship is best represented using Inheritance but If you just want
to use the services of another class use Composition.

What will happen if you call return statement or System.exit on try or catch block ?
will finally block execute?
finally block will execute even if you put return statement in try block or catch block but
finally block won’t run if you call System.exit form try or catch.

If a method throws NullPointerException in super class, can we override it with a
method which throws RuntimeException?
you can very well throw super class of RuntimeException in overridden method but you
can not do same if its checked Exception.

How do you handle error condition while writing stored procedure or accessing
stored procedure from java?
stored procedure should return error code if some operation fails but if stored procedure
itself fail than catching SQLException is only choice.

Does it matter in what order catch statements for FileNotFoundException and
IOExceptipon are written?
Yes, it does. The FileNotFoundException is inherited from the IOException. Exception’s
subclasses have to be caught first.

What if there is a break or return statement in try block followed by finally block?
If there is a return statement in the try block, the finally block executes right after the
return statement encountered, and before the return executes.

What is Inheritance ?
Inheritance is one of the main features of any object oriented programming. Using
inheritance concept, a class (Sub Class) can inherit properties of another class (Super
Class). So it is used for reuse features.

Main advantage of using Inheritance ?
Using this feature you can reuse features, less memory wastage, less time required to
develop and application and improve performance of application.

Types of Inheritance supported by Java ?
Java support only four types of inheritance in java.
 Single Inheritance
 Multi level Inheritance
 Hybrid Inheritance
 Hierarchical Inheritance

Why use Inheritance ?
 For Code Re usability.
 For class Re usability.
 For Method Overriding.

What is multilevel inheritance ?
Getting the properties from one class object to another class object level wise with
different priorities.

What is Multiple Inheritance ?
The concept of Getting the properties from multiple class objects to sub class object with
same priorities is known as multiple inheritance.

Why Java Doesn’t Support multiple Inheritance ?
Due to ambiguity problem.

What happens if super class and sub class having same field name ?
Super class field will be hidden in the sub class. You can access hidden super class field
in sub class using super keyword.

Can we reduce the visibility of the inherited or overridden method ?
Ans. No.

Which of the following is tightly bound ? Inheritance or Composition ?
Ans. Inheritance.

Does a class inherit the constructor of its super class ?
Ans. No

How Inheritance can be implemented in java?
Inheritance can be implemented in JAVA using below two keywords:
extends is used for developing inheritance between two classes and two interfaces.
implements keyword is used to developed inheritance between interface and class.

What is the difference between Inheritance and Encapsulation?
Inheritance is an object oriented concept which creates a parent-child relationship. It is
one of the ways to reuse the code written for parent class but it also forms the basis of
Polymorphism. On the other hand, Encapsulation is an object oriented concept which is
used to hide the internal details of a class e.g. HashMap encapsulate how to store
elements and how to calculate hash values.

What is the difference between Inheritance and Abstraction?
Abstraction is an object oriented concept which is used to simply things by abstracting
details. It helps in the designing system. On the other hand, Inheritance allows code reuse.
You can reuse the functionality you have already coded by using Inheritance.

Leave a Comment