Hi Guyz, here we have mentioned commonly Asked Java Programming Interview Questions. These Java Interview Questions have been designed especially to get you acquainted with the nature of questions you may be asked during your interview for the subject of Java Programming Language.If there is any core java interview question that have been asked to you, kindly post it in the the comment section.

The answers of the core java interview questions are short and to the point.As per my experience, good interviewers hardly planned to ask any particular question during your interview, normally questions start with some basic concept of the subject and later they continue based on further discussion and what you answer.


1.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).

2.What is Abstraction?


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

3.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.

4.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 Implementation.
  • Encapsulation is the deliverables of Abstraction. Encapsulation barely talks about grouping up your abstraction to suit the developer needs.

5.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:

  1. To promote code reuse
  2. To use polymorphism

6.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.

7.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 name.

  • 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).

8.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.
Note: 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

9.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.

10.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


11.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

12.What are the differences between method overloading and method overriding?



Overloaded Method

Overridden Method


Must change

Must not change

Return type

Can change

Can’t change except for covariant returns


Can change

Can reduce or eliminate. Must not throw new or broader checked exceptions


Can change

Must not make more restrictive (can be less restrictive)


Reference type determines which overloaded version is selected. Happens at compile time.

Object type determines which method is selected. Happens at runtime.

13.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.

14.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.

15.Is it possible to override the main method?


NO, because main is a static method. A static method can’t be overridden in Java.

16.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

17.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 this.xxx variables or methods to compute its parameters.

18.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


19.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.

20.Can we instantiate an interface?


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


21.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.

22.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 example.

23.What modifiers are allowed for methods in an Interface?


Only public and abstract modifiers are allowed for methods in interfaces.

24.What is a marker interface?


Marker interfaces are those which do not declare any required methods, but signify their compatibility with certain operations. The java.io.Serializableinterface 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.

25.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.

26.Can we instantiate an abstract class?


An abstract class can never be instantiated. Its sole purpose is to be extended (subclassed).

27.What are the differences between Interface and Abstract class?


Abstract Class


An abstract class can provide complete, default code and/or just the details that have to be overridden.

An interface cannot provide any code at all,just the signature.

In case of abstract class, a class may extend only one abstract class.

A Class may implement several interfaces.

An abstract class can have non-abstract methods.

All methods of an Interface are abstract.

An abstract class can have instance variables.

An Interface cannot have instance variables.

An abstract class can have any visibility: public, private, protected.

An Interface visibility must be public (or) none.

If we add a new method to an abstract class then we have the option of providing default implementation and therefore all the existing code might work properly.

If we add a new method to an Interface then we have to track down all the implementations of the interface and define implementation for the new method.

An abstract class can contain constructors .

An Interface cannot contain constructors .

Abstract classes are fast.

Interfaces are slow as it requires extra indirection to find corresponding method in the actual class.

28.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.

29.When you declare a method as abstract, can other nonabstract methods access it?


Yes, other nonabstract methods can access a method that you declare as abstract.

30.Can there be an abstract class with no abstract methods in it?


Yes, there can be an abstract class without abstract methods.


31.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.

32.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 itself.

33.Can constructor be inherited?


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

34.What are the differences between Contructors and Methods?





Create an instance of a class

Group Java statements


Cannot be abstract, final, native, static, or synchronized

Can be abstract, final, native, static, or synchronized

Return Type

No return type, not even void

void or a valid return type


Same name as the class (first letter is capitalized by convention) — usually a noun

Any name except the class. Method names begin with a lowercase letter by convention — usually the name of an action


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.


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


Constructors are not inherited

Methods are inherited

35.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.

36.What are the differences between Class Methods and Instance Methods?


Class Methods

Instance Methods

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.

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.

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 static.

37.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.

38.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.

39.What are Access Specifiers available in Java?


Java offers four access specifiers, listed below in decreasing accessibility:

  • Publicpublic classes, methods, and fields can be accessed from everywhere.
  • Protectedprotected 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 package.
  • 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.
  • Privateprivate 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.






Accessible to class

from same package?





Accessible to class

from different package?


no, unless it is a subclass



40.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.


41.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 code.

42.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.

43.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.

44.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.

45.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.

46.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 organized.
  • Iterator is an Interface implemented a different way for every Collection.

47.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() method.
  • 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().

48.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.

49.What is the difference between Enumeration and Iterator?




Enumeration doesn’t have a remove() method

Iterator has a remove() method

Enumeration acts as Read-only interface, because it has the methods only to traverse and fetch the objects

Can be abstract, final, native, static, or synchronized

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

50.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


51.What is the List interface?


  • The List interface provides support for ordered collections of objects.

Lists may contain duplicate elements.

52.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).

53.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.

54.Difference between ArrayList and Vector ?




ArrayList is NOT synchronized by default.

Vector List is synchronized by default.

ArrayList can use only Iterator to access the elements.

Vector list can use Iterator and Enumeration Interface to access the elements.

The ArrayList increases its array size by 50 percent if it runs out of room.

A Vector defaults to doubling the size of its array if it runs out of room

ArrayList has no default size.

While vector has a default size of 10.

55.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();

56.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.

57.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.

58.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.

59.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

60.What are the main Implementations of the Set interface ?


The main implementations of the List interface are as follows:

  • HashSet
  • TreeSet
  • LinkedHashSet
  • EnumSet


61.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.

62.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.

63.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.

64.Difference between HashSet and TreeSet ?




HashSet is under set interface i.e. it  does not guarantee for either sorted order or sequence order.

TreeSet is under set i.e. it provides elements in a sorted  order (acceding order).

We can add any type of elements to hash set.

We can add only similar types

of elements to tree set.

65.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.

66.What are the main Implementations of the Map interface ?


The main implementations of the List interface are as follows:

  • HashMap
  • HashTable
  • TreeMap
  • EnumMap

67.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.

68.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.

69.Difference between HashMap and Hashtable ?




HashMap lets you have null values as well as one null key.

HashTable  does not allows null values as key and value.

The iterator in the HashMap is fail-safe (If you change the map while iterating, you’ll know).

The enumerator for the Hashtable is not fail-safe.

HashMap is unsynchronized.

Hashtable is synchronized.

Note: Only one NULL is allowed as a key in HashMap. HashMap does not allow multiple keys to be NULL. Nevertheless, it can have multiple NULL values.

70.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.


71.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.

72.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.

73.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.

74.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.

75.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).

76.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

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 thecompareTo() 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.

77.What are the differences between the Comparable and Comparator interfaces ?




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.

Many sort sequences can be created.

It is frequently used by the API classes.

It used by third-party classes to sort instances.

78. What are the important features of Java 10 release?


Java 10 is the first every-six-months from Oracle corporation, so it’s not a major release like earlier versions. However some of the important features of Java 10 are:

  • Local-Variable Type Inference.
  • Enhance java.util.Locale and related APIs to implement additional Unicode extensions of BCP 47 language tags.
  • Enable the HotSpot VM to allocate the Java object heap on an alternative memory device, such as an NV-DIMM, specified by the user.
  • Provide a default set of root Certification Authority (CA) certificates in the JDK.
  • Java 10 is mostly a maintenance release, however I really liked the local variable type inference feature.

79. What are the important features of Java 9 release?


Java 9 was a major release and brought a lot of features. Some of the important features are:

  • Java 9 REPL (JShell)
  • Java 9 Module System
  • Factory Methods for Immutable List, Set, Map and Map.Entry
  • Private methods in Interfaces
  • Reactive Streams
  • GC (Garbage Collector) Improvements

80. What are the important features of Java 8 release?


  • Java 8 has been released in March 2014, so it’s one of the hot topic in java interview questions. If you answer this question clearly, it will show that you like to keep yourself up-to-date with the latest technologies.
  • Java 8 has been one of the biggest release after Java 5 annotations and generics. Some of the important features of Java 8 are:
  • Interface changes with default and static methods
  • Functional interfaces and Lambda Expressions
  • Java Stream API for collection classes
  • Java Date Time API
  • I strongly recommend to go through above links to get proper understanding of each one of them, also read Java 8 Features.


81. Name some OOPS Concepts in Java?


Java is based on Object Oriented Programming Concepts, following are some of the OOPS concepts implemented in java programming.

  • Abstraction
  • Encapsulation
  • Polymorphism
  • Inheritance
  • Association
  • Aggregation
  • Composition

82. What do you mean by platform independence of Java?


Platform independence means that you can run the same Java Program in any Operating System. For example, you can write java program in Windows and run it in Mac OS.

83. What is JVM and is it platform independent?


Java Virtual Machine (JVM) is the heart of java programming language. JVM is responsible for converting byte code into machine readable code. JVM is not platform independent, thats why you have different JVM for different operating systems. We can customize JVM with Java Options, such as allocating minimum and maximum memory to JVM. It’s called virtual because it provides an interface that doesn’t depend on the underlying OS.

84. What is the difference between JDK and JVM?


Java Development Kit (JDK) is for development purpose and JVM is a part of it to execute the java programs.

JDK provides all the tools, executables and binaries required to compile, debug and execute a Java Program. The execution part is handled by JVM to provide machine independence.

85. What is the difference between JVM and JRE?


Java Runtime Environment (JRE) is the implementation of JVM. JRE consists of JVM and java binaries and other classes to execute any program successfully. JRE doesn’t contain any development tools like java compiler, debugger etc. If you want to execute any java program, you should have JRE installed.

86. Which class is the superclass of all classes?


java.lang.Object is the root class for all the java classes and we don’t need to extend it.

87. Why Java doesn’t support multiple inheritance?


Java doesn’t support multiple inheritance in classes because of “Diamond Problem”. To know more about diamond problem with example, read Multiple Inheritance in Java.

However multiple inheritance is supported in interfaces. An interface can extend multiple interfaces because they just declare the methods and implementation will be present in the implementing class. So there is no issue of diamond problem with interfaces.

88. Why Java is not pure Object Oriented language?


Java is not said to be pure object oriented because it support primitive types such as int, byte, short, long etc. I believe it brings simplicity to the language while writing our code. Obviously java could have wrapper objects for the primitive types but just for the representation, they would not have provided any benefit.

As we know, for all the primitive types we have wrapper classes such as Integer, Long etc that provides some additional methods.

89. What is difference between path and classpath variables?


PATH is an environment variable used by operating system to locate the executables. That’s why when we install Java or want any executable to be found by OS, we need to add the directory location in the PATH variable. If you work on Windows OS, read this post to learn how to setup PATH variable on Windows.

Classpath is specific to java and used by java executables to locate class files. We can provide the classpath location while running java application and it can be a directory, ZIP files, JAR files etc.

90. What is the importance of main method in Java?


main() method is the entry point of any standalone java application. The syntax of main method is public static void main(String args[]).

main method is public and static so that java can access it without initializing the class. The input parameter is an array of String through which we can pass runtime arguments to the java program. Check this post to learn how to compile and run java program.


91. Method in Java?


public static void main(String[] args) Java main method is the entry point of any java program. Its syntax is always public static void main(String[] args) . You can only change the name of String array argument, for example you can change args to myStringArgs .

92. What is overloading and overriding in java?


When we have more than one method with same name in a single class but the arguments are different, then it is called as method overloading.
Overriding concept comes in picture with inheritance when we have two methods with same signature, one in parent class and another in child class. We can use @Override annotation in the child class overridden method to make sure if parent class method is changed, so as child class.

93. Can we overload main method?


Yes, we can have multiple methods with name “main” in a single class. However if we run the class, java runtime environment will look for main method with syntax as public static void main(String args[]).

94. Can we have multiple public classes in a java source file?


We can’t have more than one public class in a single java source file. A single source file can have multiple classes that are not public.

95. What is Java Package and which package is imported by default?


Java package is the mechanism to organize the java classes by grouping them. The grouping logic can be based on functionality or modules based. A java class fully classified name contains package and class name. For example, java.lang.Object is the fully classified name of Object class that is part of java.lang package.

java.lang package is imported by default and we don’t need to import any class from this package explicitly.

96. What are access modifiers?


Java provides access control through public, private and protected access modifier keywords. When none of these are used, it’s called default access modifier.
A java class can only have public or default access modifier.

97. What is final keyword?


final keyword is used with Class to make sure no other class can extend it, for example String class is final and we can’t extend it.

We can use final keyword with methods to make sure child classes can’t override it.

final keyword can be used with variables to make sure that it can be assigned only once. However the state of the variable can be changed, for example we can assign a final variable to an object only once but the object variables can change later on.

Java interface variables are by default final and static.

98. What is static keyword?


static keyword can be used with class level variables to make it global i.e all the objects will share the same variable.

static keyword can be used with methods also. A static method can access only static variables of class and invoke only static methods of the class.

99. What is finally and finalize in java?


finally block is used with try-catch to put the code that you want to get executed always, even if any exception is thrown by the try-catch block. finally block is mostly used to release resources created in the try block.

finalize() is a special method in Object class that we can override in our classes. This method get’s called by garbage collector when the object is getting garbage collected. This method is usually overridden to release system resources when object is garbage collected.

100. Can we declare a class as static?


We can’t declare a top-level class as static however an inner class can be declared as static. If inner class is declared as static, it’s called static nested class.
Static nested class is same as any other top-level class and is nested for only packaging convenience.


101. What is static import?


If we have to use any static variable or method from other class, usually we import the class and then use the method/variable with class name.

import java.lang.Math;

//inside class

double test = Math.PI * 5;

We can do the same thing by importing the static method or variable only and then use it in the class as if it belongs to it.

import static java.lang.Math.PI;

//no need to refer class now

double test = PI * 5;

Use of static import can cause confusion, so it’s better to avoid it. Overuse of static import can make your program unreadable and unmaintainable.

102. What is try-with-resources in java?


One of the Java 7 features is try-with-resources statement for automatic resource management. Before Java 7, there was no auto resource management and we should explicitly close the resource. Usually, it was done in the finally block of a try-catch statement. This approach used to cause memory leaks when we forgot to close the resource.

From Java 7, we can create resources inside try block and use it. Java takes care of closing it as soon as try-catch block gets finished.

103. What is multi-catch block in java?


Java 7 one of the improvement was multi-catch block where we can catch multiple exceptions in a single catch block. This makes are code shorter and cleaner when every catch block has similar code.
If a catch block handles multiple exception, you can separate them using a pipe (|) and in this case exception parameter (ex) is final, so you can’t change it.

104. What is static block?


Java static block is the group of statements that gets executed when the class is loaded into memory by Java ClassLoader. It is used to initialize static variables of the class. Mostly it’s used to create static resources when class is loaded.

105. What is an interface?


Interfaces are core part of java programming language and used a lot not only in JDK but also java design patterns, most of the frameworks and tools. Interfaces provide a way to achieve abstraction in java and used to define the contract for the subclasses to implement.

Interfaces are good for starting point to define Type and create top level hierarchy in our code. Since a java class can implements multiple interfaces, it’s better to use interfaces as super class in most of the cases.

106. What is an abstract class?


Abstract classes are used in java to create a class with some default method implementation for subclasses. An abstract class can have abstract method without body and it can have methods with implementation also.

abstract keyword is used to create a abstract class. Abstract classes can’t be instantiated and mostly used to provide base for sub-classes to extend and implement the abstract methods and override or use the implemented methods in abstract class.

107. What is the difference between abstract class and interface?


abstract keyword is used to create abstract class whereas interface is the keyword for interfaces.

Abstract classes can have method implementations whereas interfaces can’t.

A class can extend only one abstract class but it can implement multiple interfaces.

We can run abstract class if it has main() method whereas we can’t run an interface.

108. Can an interface implement or extend another interface?


Interfaces don’t implement another interface, they extend it. Since interfaces can’t have method implementations, there is no issue of diamond problem. That’s why we have multiple inheritance in interfaces i.e an interface can extend multiple interfaces.

From Java 8 onwards, interfaces can have default method implementations. So to handle diamond problem when a common default method is present in multiple interfaces, it’s mandatory to provide implementation of the method in the class implementing them.

109. What is Marker interface?


A marker interface is an empty interface without any method but used to force some functionality in implementing classes by Java. Some of the well known marker interfaces are Serializable and Cloneable.

110. What are Wrapper classes?


Java wrapper classes are the Object representation of eight primitive types in java. All the wrapper classes in java are immutable and final. Java 5 autoboxing and unboxing allows easy conversion between primitive types and their corresponding wrapper classes.


111. What is Enum in Java?


Enum was introduced in Java 1.5 as a new type whose fields consists of fixed set of constants. For example, in Java we can create Direction as enum with fixed fields as EAST, WEST, NORTH, SOUTH.

enum is the keyword to create an enum type and similar to class. Enum constants are implicitly static and final.

112. What is Java Annotations?


Java Annotations provide information about the code and they have no direct effect on the code they annotate. Annotations are introduced in Java 5. Annotation is metadata about the program embedded in the program itself. It can be parsed by the annotation parsing tool or by compiler. We can also specify annotation availability to either compile time only or till runtime also. Java Built-in annotations are @Override, @Deprecated and @SuppressWarnings. 

113. What is Java Reflection API? Why it’s so important to have?


Java Reflection API provides ability to inspect and modify the runtime behavior of java application. We can inspect a java class, interface, enum and get their methods and field details. Reflection API is an advanced topic and we should avoid it in normal programming. Reflection API usage can break the design pattern such as Singleton pattern by invoking the private constructor i.e violating the rules of access modifiers.

Even though we don’t use Reflection API in normal programming, it’s very important to have. We can’t have any frameworks such as Spring, Hibernate or servers such as Tomcat, JBoss without Reflection API. They invoke the appropriate methods and instantiate classes through reflection API and use it a lot for other processing.

114. What is composition in java?


Composition is the design technique to implement has-a relationship in classes. We can use Object composition for code reuse.

Java composition is achieved by using instance variables that refers to other objects. Benefit of using composition is that we can control the visibility of other object to client classes and reuse only what we need.

115. What is the benefit of Composition over Inheritance?


One of the best practices of java programming is to “favor composition over inheritance”. Some of the possible reasons are:

Any change in the superclass might affect subclass even though we might not be using the superclass methods. For example, if we have a method test() in subclass and suddenly somebody introduces a method test() in superclass, we will get compilation errors in subclass. Composition will never face this issue because we are using only what methods we need.
Inheritance exposes all the super class methods and variables to client and if we have no control in designing superclass, it can lead to security holes. Composition allows us to provide restricted access to the methods and hence more secure.
We can get runtime binding in composition where inheritance binds the classes at compile time. So composition provides flexibility in invocation of methods.

116. How to sort a collection of custom Objects in Java?


We need to implement Comparable interface to support sorting of custom objects in a collection. Comparable interface has compareTo(T obj) method which is used by sorting methods and by providing this method implementation, we can provide default way to sort custom objects collection.

However, if you want to sort based on different criteria, such as sorting an Employees collection based on salary or age, then we can create Comparator instances and pass it as sorting methodology.

117. What is inner class in java?


We can define a class inside a class and they are called nested classes. Any non-static nested class is known as inner class. Inner classes are associated with the object of the class and they can access all the variables and methods of the outer class. Since inner classes are associated with instance, we can’t have any static variables in them.

We can have local inner class or anonymous inner class inside a class.

118. What is Classloader in Java?


Java Classloader is the program that loads byte code program into memory when we want to access any class. We can create our own classloader by extending ClassLoader class and overriding loadClass(String name) method.

119. What are different types of classloaders?


There are three types of built-in Class Loaders in Java:

Bootstrap Class Loader – It loads JDK internal classes, typically loads rt.jar and other core classes.
Extensions Class Loader – It loads classes from the JDK extensions directory, usually $JAVA_HOME/lib/ext directory.
System Class Loader – It loads classes from the current classpath that can be set while invoking a program using -cp or -classpath command line options.

120. What is ternary operator in java?


Java ternary operator is the only conditional operator that takes three operands. It’s a one liner replacement for if-then-else statement and used a lot in java programming. We can use ternary operator if-else conditions or even switch conditions using nested ternary operators. An example can be found at java ternary operator.


121. What does super keyword do?


super keyword can be used to access super class method when you have overridden the method in the child class.

We can use super keyword to invoke super class constructor in child class constructor but in this case it should be the first statement in the constructor method.

package com.journaldev.access;

public class SuperClass {

public SuperClass(){

public SuperClass(int i){}

public void test(){
System.out.println(“super class test method”);
Use of super keyword can be seen in below child class implementation.

package com.journaldev.access;

public class ChildClass extends SuperClass {

public ChildClass(String str){
//access super class constructor with super keyword

//access child class method

//use super to access super class method

public void test(){
System.out.println(“child class test method”);

122. What is break and continue statement?


We can use break statement to terminate for, while, or do-while loop. We can use break statement in switch statement to exit the switch case. You can see the example of break statement at java break. We can use break with label to terminate the nested loops.

The continue statement skips the current iteration of a for, while or do-while loop. We can use continue statement with label to skip the current iteration of outermost loop.

123. What is this keyword?


this keyword provides reference to the current object and it’s mostly used to make sure that object variables are used, not the local variables having same name.

public Point(int x, int y) {
this.x = x;
this.y = y;
We can also use this keyword to invoke other constructors from a constructor.

public Rectangle() {
this(0, 0, 0, 0);
public Rectangle(int width, int height) {
this(0, 0, width, height);
public Rectangle(int x, int y, int width, int height) {
this.x = x;
this.y = y;
this.width = width;
this.height = height;

124. What is default constructor?


No argument constructor of a class is known as default constructor. When we don’t define any constructor for the class, java compiler automatically creates the default no-args constructor for the class. If there are other constructors defined, then compiler won’t create default constructor for us.

125. Can we have try without catch block?


Yes, we can have try-finally statement and hence avoiding catch block.

126. What is Garbage Collection?


Garbage Collection is the process of looking at heap memory, identifying which objects are in use and which are not, and deleting the unused objects. In Java, process of deallocating memory is handled automatically by the garbage collector.

We can run the garbage collector with code Runtime.getRuntime().gc() or use utility method System.gc(). For a detailed analysis of Heap Memory and Garbage Collection, please read Java Garbage Collection.

127. What is Serialization and Deserialization?


We can convert a Java object to an Stream that is called Serialization. Once an object is converted to Stream, it can be saved to file or send over the network or used in socket connections.

The object should implement Serializable interface and we can use java.io.ObjectOutputStream to write object to file or to any OutputStream object.

The process of converting stream data created through serialization to Object is called deserialization.

128. How to run a JAR file through command prompt?


We can run a jar file using java command but it requires Main-Class entry in jar manifest file. Main-Class is the entry point of the jar and used by java command to execute the class.

129. What is the use of System class?


Java System Class is one of the core classes. One of the easiest way to log information for debugging is System.out.print() method.

System class is final so that we can’t subclass and override it’s behavior through inheritance. System class doesn’t provide any public constructors, so we can’t instantiate this class and that’s why all of it’s methods are static.

Some of the utility methods of System class are for array copy, get current time, reading environment variables.

130. What is instanceof keyword?


We can use instanceof keyword to check if an object belongs to a class or not. We should avoid it’s usage as much as possible. Sample usage is:

public static void main(String args[]){
Object str = new String("abc");

if(str instanceof String){
System.out.println(“String value:”+str);

if(str instanceof Integer){
System.out.println(“Integer value:”+str);

Since str is of type String at runtime, first if statement evaluates to true and second one to false.


131. Can we use String with switch case?


One of the Java 7 feature was improvement of switch case of allow Strings. So if you are using Java 7 or higher version, you can use String in switch-case statements.

132. Java is Pass by Value or Pass by Reference?


This is a very confusing question, we know that object variables contain reference to the Objects in heap space. When we invoke any method, a copy of these variables is passed and gets stored in the stack memory of the method. We can test any language whether it’s pass by reference or pass by value through a simple generic swap method

133. What is difference between Heap and Stack Memory?


Major difference between Heap and Stack memory are as follows:

Heap memory is used by all the parts of the application whereas stack memory is used only by one thread of execution.
Whenever an object is created, it’s always stored in the Heap space and stack memory contains the reference to it. Stack memory only contains local primitive variables and reference variables to objects in heap space.
Memory management in stack is done in LIFO manner whereas it’s more complex in Heap memory because it’s used globally.

134. Java Compiler is stored in JDK, JRE or JVM?


The task of java compiler is to convert java program into bytecode, we have javac executable for that. So it must be stored in JDK, we don’t need it in JRE and JVM is just the specs.

135. What will be the output of following programs?

static method in class
package com.journaldev.util;

public class Test {

public static String toString(){
System.out.println(“Test toString called”);
return “”;

public static void main(String args[]){


The code won’t compile because we can’t have an Object class method with static keyword. Note that Object class has toString() method. You will get compile time error as “This static method cannot hide the instance method from Object”. The reason is that static method belongs to class and since every class base is Object, we can’t have same method in instance as well as in class. You won’t get this error if you change the method name from toString() to something else that is not present in super class Object.

136. Static method invocation

package com.journaldev.util;

public class Test {

public static String foo(){
System.out.println(“Test foo called”);
return “”;

public static void main(String args[]){
Test obj = null;


Well this is a strange situation. We all have seen NullPointerException when we invoke a method on object that is NULL. But here this program will work and prints “Test foo called”.

The reason for this is the java compiler code optimization. When the java code is compiled to produced byte code, it figures out that foo() is a static method and should be called using class. So it changes the method call obj.foo() to Test.foo() and hence no NullPointerException.

137.What is Busy Spinning? Why Should You Use It in Java?


One of the interesting multithreading question to senior Java programmers, busy spinning is a waiting strategy, in which a thread just wait in a loop, without releasing the CPU for going to sleep. This is a very advanced and specialized waiting strategy used in the high-frequency trading application when wait time between two messages is very minimal.

By not releasing the CPU or suspending the thread, your thread retains all the cached data and instruction, which may be lost if the thread was suspended and resumed back in a different core of CPU.

This question is quite popular in high-frequency low latency programming domain, where programmers are trying for extremely low latency in the range of micro to milliseconds

138. What is Read-Write Lock? Does ConcurrentHashMap in Java Uses The ReadWrite Lock?


ReadWrite Lock is an implementation of lock stripping technique, where two separate locks are used for read and write operation. Since read operation doesn’t modify the state of the object, it’s safe to allow multiple thread access to a shared object for reading without locking, and by splitting one lock into read and write lock, you can easily do that.

Java provides an implementation of read-write lock in the form of ReentrantReadWritLock class in the java.util.concurrent.lock package. This is worth looking before you decide to write your own read-write locking implementation.

Also, the current implementation of java.util.ConcurrentHashMap doesn’t use the ReadWriteLock, instead, it divides the Map into several segments and locks them separately using different locks. This means any given time, only a portion of the ConcurrentHashMap is locked, instead of the whole Map.

This core Java question is also very popular on senior and more experienced level Java interviews e.g. 4 to 6 years, where you expect Interviewer to go into more detail, e.g. by asking you to provided an implementation of the read-write lock with different policies. If you are an experienced Java programmer, consider reading Java Concurrency in Practice to gain more confidence about multithreading and concurrency in Java.

139. How to Make an Object Immutable in Java? Why Should You Make an Object Immutable?


Well, Immutability offers several advantages including thread-safety, ability to cache and result in more readable multithreading code. Once again, this question can also go into more detail and depending on your answer, can bring several other questions e.g. when you mention Spring is Immutable, be ready with some reasons on Why String is Immutable in Java.

140. Which Design Patterns have You Used in Your Java Project?


Always expect some design patterns related question for Core Java Interview of senior developer position. It’s a better strategy to mention any GOF design pattern rather than Singleton or MVC, which almost every other Java developer use it.

Your best bet can be Decorator pattern or may be Dependency Injection Pattern, which is quite popular in Spring Framework. It’s also good to mention only the design patterns which you have actually used in your project and knows it’s tradeoffs.

It’s common that once you mention a particular design pattern say Factory or Abstract Factory, Interviewer’s next question would be, have you used this pattern in your project? So be ready with proper example and why you choose a particular pattern.


141. Do you know about Open Closed Design Principle or Liskov Substitution Principle?


Design patterns are based on object-oriented design principles, which I strongly felt every object-oriented developer and the programmer should know, or, at least, have a basic idea of what are these principles and how they help you to write better object oriented code. I

f you don’t know the answer to this question, you can politely say No, as it’s not expected from you to know the answer to every question, but by answering this question, you can make your claim stronger as many experienced developers fail to answer basic questions like this. 

142. Which Design Pattern Will You Use to Shield Your Code From a Third Party library Which Will Likely to be Replaced by Another in Couple of Months?


This is just one example of the scenario-based design pattern interview question. In order to test the practical experience of Java developers with more than 5 years experience, companies ask this kind of questions. You can expect more real-world design problems in different formats, some with more detail explanation with context, or some with only intent around.

One way to shield your code from third party library is to code against an interface rather than implementation and then use dependency injection to provide a particular implementation. This kind of questions is also asked quite frequently to experienced and senior Java developers with 5 to 7 years of experience.

143. How do you prevent SQL Injection in Java Code?


This question is more asked to J2EE and Java EE developers than core Java developers, but, it is still a good question to check the JDBC and Security skill of experienced Java programmers.

You can use PreparedStatement to avoid SQL injection in Java code. Use of the PreparedStatement for executing SQL queries not only provides better performance but also shield your Java and J2EE application from SQL Injection attack.

On a similar note, If you are working more on Java EE or J2EE side, then you should also be familiar with other security issues including Session Fixation attack or Cross Site Scripting attack and how to resolve them. These are some fields and questions where a good answer can make a lot of difference on your selection.

144. How does get method of HashMap works in Java?


Yes, this is still one of the most popular core Java questions for senior developer interviews. You can also expect this question on telephonic round, followed by lot’s of follow-up questions as discussed on my post how does HashMap work in Java.

The short answer to this question is that HashMap is based upon hash table data structure and uses hashCode() method to calculate hash code to find the bucket location on underlying array and equals() method to search the object in the same bucket in case of a collision.

145. Which Two Methods HashMap key Object Should Implement?


This is one of the follow-up questions I was saying about in previous questions. Since working of HashMap is based upon hash table data structure, any object which you want to use as key for HashMap or any other hash based collection e.g. Hashtable, or ConcurrentHashMap must implement equals() and hashCode() method.

The hashCode() is used to find the bucket location i.e. index of underlying array and equals() method is used to find the right object in linked list stored in the bucket in case of a collision. By the way, from Java 8, HashMap also started using tree data structure to store the object in case of collision to reduce worst case performance of HashMap from O(n) to O(logN).

146. Why Should an Object Used As the Key should be Immutable?


This is another follow-up of previous core Java interview questions. It’s good to test the depth of technical knowledge of candidate by asking more and more question on the same topic. If you know about Immutability, you can answer this question by yourself. The short answer to this question is key should be immutable so that hashCode() method always return the same value.

Since hash code returned by hashCode() method depends on upon the content of object i.e. values of member variables. If an object is mutable than those values can change and so is the hash code. If the same object returns different hash code once you inserted the value in HashMap, you will end up searching in different bucket location and will not able to retrieve the object. That’s why a key object should be immutable. It’s not a rule enforced by the compiler but you should take care of it as an experienced programmer.

147. How does ConcurrentHashMap achieves its Scalability?


Sometimes this multithreading + collection interview question is also asked as, the difference between ConcurrentHashMap and Hashtable in Java. The problem with synchronized HashMap or Hashtable was that whole Map is locked when a thread performs any operation with Map.

The java.util.ConcurrentHashMap class solves this problem by using lock stripping technique, where the whole map is locked at different segments and only a particular segment is locked during the write operation, not the whole map. The ConcurrentHashMap also achieves it’s scalability by allowing lock-free reads as read is a thread-safe operation.

148. How do you share an object between threads? or How to pass an object from one thread to another?


There are multiple ways to do that e.g. Queues, Exchanger etc, but BlockingQueue using Producer Consumer pattern is the easiest way to pass an object from thread to another.

149. How do find if your program has a deadlock?


By taking thread dump using kill -3, using JConsole or VisualVM), I suggest to prepare this core java interview question in more detail, as Interviewer definitely likes to go with more detail e.g. they will press with questions like, have you really done that in your project or not?

150. How do you avoid deadlock while coding?


By ensuring locks are acquire and released in an ordered manner.