Top 150+ Java Interview Questions and Answers

    58 Votes

Are you preparing for Java Interview? If so, you are at the right place. This article provides frequently asked Java Interview Questions and Answers on basic & advanced topics covering all the core Java concepts like JVM, JRE, Operators, OOPs, Exceptions, IO operations, Collections etc. for Freshers and experienced Java developers.

1. What is Java technology ?

Java is a programming language, application development and deployment environment. The Java programming language is similar to C++ syntax. Java development environment provides tools for Compiling, Interpreting, Packaging the Java code.

2. What are the objectives of Java Technology ?
Java interview questions
Simple: The language syntax is based on ‘C++’ programming language. Even though the syntax of ‘C++ was adopted, some features which were troublesome were avoided to make the Java programming simple.
Object oriented: The object oriented features of Java are similar to C++. One major difference between Java and C++ lies in multiple inheritance. When C++ supports multiple inheritance, Java won't. In OOPs programming paradigm, everything is represented as Class and Objects.
Architectural Neutral: The Java compiler generates an intermediate byte code which doesn't depend on the operating system on which it is run. So the Java programs can run on any machine, irrespective of it's OS/Architecture and hence the Java program is Architectural Neutral.
Portable type: The size of Data Types is always same irrespective of the system architecture. An int in Java will always be 32 bit unlike in C/C++ where the size may be 16-bit or 32-bit depending on the compiler and machine. Java have libraries that enable to port it's application to any systems like UNIX, Windows & Macintosh systems.
Distributed: Java’s networking capabilities are both strong and easy to use. Java applications are capable of accessing objects across the net and local file system.
Secure: Since Java is mostly used in a network environment, a lot of emphasis has been placed on security to enable construction of virus & tamper free systems.
Smaller code: The Java compiler generates an intermediate byte code to make it architecture neutral. Though Java interpreter is needed to run the byte code, it is one copy per machine and not per program.
Multithreaded: Multithreading is the ability for one program to do more than one task at once. Compared to other languages it is easy to implement multithreading in Java.
Interpreted: The Java Interpreter can execute Java byte code, directly on any machine to which the interpreter has been ported. Interpreted code is slower than compiled code.

High performance: The byte codes can be translated at run time into machine code for the particular CPU on which the application is running which inturn provide high performance.

Applet programming: is one of the important features which has attracted the users of the Internet. Applets are Java programs that are typically loaded from the Internet by a browser.

3. What are the Major Features of Java Technology Architecture ?
  • Java Run Time Environment
  • Java Virtual Machine
  • Just in Time Compiler
  • Java Tools
  • Garbage Collector
Related Java Interview Questions
1. Java Collections Interview Questions
2. Java Thread Interview Questions
3. Java OOPS Interview Questions
4. Advanced Java Interview Questions
5. JSP Interview Questions
6. Servlet Interview Questions

Java Basics Interview Questions - JVM, JRE & JDK

4. What is Java Virtual Machine (JVM) ?

A self-contained operating environment that behaves as if it is a separate computer. For example, Java applets run in a Java virtual machine (VM) that has no access to the host operating system.

5. What are the advantages of JVM?

This design has two advantages:

  • System Independence: A Java application will run the same in any Java VM, regardless of the hardware and software underlying the system. 
  • Security: Because the JVM has no contact with the operating system, there is little possibility of a Java program damaging other files or applications.

6. What are classpath variables?

The classpath is an environment variable that tells the JVM where to look for user-defined classes and packages in Java programs. When a Java program is executed, JVM looks for the required classes needed for the program execution in the filesystem specified in the Classpath. Classes are loaded into the JVM, only when a call is made to use the content of the class object(Lazy Loading).

7. Explain the architecture of code execution process inside JRE ?

Java Architecture and Compilation

Java Compilers compile JAVA source code into byte code. Java Virtual Machine(JVM) interpreters Java byte code and send necessary commands to underlying hardware or Just in time compiled to native machine code and execute it directly on the underlying hardware.

Most JVM's use Just in time compilation which provides execution speeds near to C/C++ application. Most widely used JVM is Oracle Corporation's HotSpot, which is written in the C++ programming language.

8. What is Java Run Time Environment ?

Java Virtual Machine (JVM) along with Java Class Libraries which implement the Java application programming interface (API) form the Java Runtime Environment (JRE).

9. What are the steps involved in Java Application Execution ?

  • Compiling Java Source Files into *.class file. (Byte Code)
  • Loading class file into Java Run Time (JRE) using class loader
  • Use Bytecode verifier to check for byte code specification
  • Use Just In time Code Generator or Interpreter for byte code execution

10. What is Just in Time Compiler ?

Just in time Compiler (JIT) compiles JAVA byte code to native machine code and execute it directly on the underlying hardware. Just-In time compilation provides application execution speeds near to C or C++ application.
11. What is Java Development Kit (JDK) ?

Java Development Kit (JDK) is a superset of the JRE, which contains Java Run-time Environment (JRE) , Compilers and debuggers required to develop applets and applications.

12. What is Garbage Collector ?
For executing programs, application allocate memory at runtime. After execution of programs, unused memory needs to be deallocated. Allocation and deallocation of memory is done by programmers developing application using C,/C++ programming language. Java internally uses a garbage collector to deallocate unused memory which makee the life of programmer easier.
13. What is class loader ?

Class loader is used to load all the classes required to execute the application into the Java Virtual Machine (JVM). Once the classes are loaded, the memory required for the application is determined.

14. What is byte code verifier ?

Byte code verifier checks for illegal code like forged pointers, violated access rights on objects etc. in complied byte code.

15. What are the java verifications done by byte code verifier ?

1. Check whether classes follow JVM specification for classes
2. Check for stack overflows
3. Check for access restriction violations
4. Illegal data conversions

16. What is Java API?

An application programming interface (API) is a library of functions that Java provides for programmers, for common tasks like file transfer, networking, and data structures.

17. Give Some examples of Java API.

  • Java.applet - Applet class
  • Java.awt - Windows, buttons, mouse, etc.
  • Java.awt.image - image processing
  • Java.awt.peer - GUI toolkit
  • - System.out.print
  • Java.lang - length method for arrays; exceptions
  • - sockets
  • Java.util - System.getProperty

18. What is an applet?

An applet is a small Java program that runs within a web page on your browser. Unlike a traditional desktop application, an applet is severely limited as to what it can perform on your desktop.

  • Applet read and write files.
  • Applet integrates with desktop services (e.g., e-mail).
  • It is connected to other servers.
  • It is also built with security in mind.
  • If the user allows, an applet can be given more authority.

Java OOPS Interview Questions and Answers

19. What is a class?

Classes are used to define objects of a certain type. For example - Car, Person etc. To define the characteristics of a class, variables and the methods are used.

20. What is an object?

An object is an instance of a classes, which has it's own private collection of properties (i.e. data) and methods (i.e. operations).

21. What an object contains?

An object has - State and Behavior

22. What is object oriented program?

An Object-Oriented Program consists of a group of cooperating objects, exchanging messages, in-order to  achieve a common objective.

23. What are the benefit's of OOPS?

  • Real-world programming
  • Reusability of code
  • Modularity of code 
  • Resilience to change
  • Information hiding

24. What are the features of OOPS?

  • Encapsulation 
  • Abstraction 
  • Inheritance 
  • Polymorphism

25. What is encapsulation?

Encapsulation helps to implement one of the four fundamental Object Oriented Programming concepts, i.e. data hiding. It is the ability of an object to bind together the data (properties) and functions that manipulate the data, safe from outside manipulations. As per Grady Booch, encapsulation is defined as: “The process of hiding all of the details of an object that do not contribute to it's essential characteristics.
26. What is abstraction?

Data Abstraction is the process of hiding unnecessary details, exposing relevant information of an object suited for the system under consideration. Best example is an interface.

27. What is the difference between encapsulation and abstraction?
Encapsulation hides the irrelevant details of an object and Abstraction makes only the relevant details of an object visible.
28. What is inheritance?

Inheritance is the capability of a class to use the properties and methods of another class while adding it's own functionality. It enables you to add new features and functionality to an existing class without modifying the existing class.

29. What is superclass and subclass?

  • A superclass or parent class is the one from which another class inherit's attributes and behavior.
  • A subclass or child class is a class that inherit's attributes and behavior from a superclass.

30. What are the types of inheritance?

  • Single inheritance 
  • Multiple inheritance

31. What is single inheritance?

Subclass is derived from only one superclass.

Single inheritance

32. What is multiple inheritance?

A subclass is derived from more than one super class

Multiple inheritance

33. What is polymorphism?

Polymorphism is defined as the ability of an object to take multiple forms depending on their type or class. The best example of Polymorphism is, invoking derived class methods through a base class reference at run-time.

34. Describe method overloading with example?

Java allows to define several methods with same name within a class, but with different method signature. Methods are identified with the parameters set based on:

  • the number of parameters
  • types of parameters and
  • order of parameters.

Example of Method overloading is as given below.

int sum(int a,int b) { return a+b;}
int sum(int a,int b,int c) { return a+b+c;}
float sum(float a, float b, float c) { return a+b+c;}

35. How to identify starting method of a program ?

Method starting with following code
public static void main (String args[])

Java Interview Questions on Classes & Packages

36. How do we access data members of a class in java?

Dot Operator(.) is used to access the data members of a class outside the class by specifying the data member name or the method name.

37. What is "this" reference in java?

To refer the current object, “this” keyword is used. When we want to pass the instance of the current object to a method in another object, we pass the current instance as shown below.
In case, a variable of an object and parameter name of a method in the object are same, we use "this" keyword to avoid ambiguity as shown below.
String name;
public void method1(String name){;
The "this" keyword included with parenthesis, i.e. this() with or without parameters is used to call another constructor. The default constructor for the Car class can be redefined as below
public Car(){

The this() can be called only from a constructor and must be the first statement in the constructor.

38. What are the uses of Java packages?

"To organize related set of classes and interfaces, a package is used. It also defines the scope of a class. An application consists of thousands of classes and interfaces, and therefore, it is very important to organize them logically into packages. By definition, package is a grouping of related types providing access protection and name space management." Packages enable you to organize the class files provided by Java.

39. What is the significance of import keyword?

To access variables and methods of a class(Car) in another class(Person), we need to include the Class "Car" in Class "Person". This is done using "import" keyword. The import keyword followed by fully qualified class name is to be placed before the application class definition.

import classname ;
// Class Definition.
Ex: import Java.util.Date;
// Class Definition
Above code tell JRE to import all the classes in a package. All the classes in Java.lang package are included implicitly.

40. What is user defined package in java?

When you write a Java program, you create many classes. You can organize these classes by creating your own packages. The packages that you create are called user-defined packages. A user-defined package contains one or more classes that can be imported in a Java program.

package land.vehicle;
public class Car
String brand;
String color;
int wheels;

41. How to compile a Java Source file ?

From the command prompt, Go to the location in which Java file is located. Enter command “javac” followed by Java source file name. For example, To compile person class, type command “javac” . Class files will be generated in the same location

42. How to compile all the files in a Folder?

javac *.java”

43. How to place compiled Java file in a different location ?

To compile Java classes and place all the files in a different location use command “javac -d ../Java/All/*.java

44. How to run a compiled  Java file ?

Go to the location in which Java file is located from command prompt. Enter command “java” followed by the class name. For example, to execute Employee class, type command

java Employee

45. Why Information hiding is used and how Information hiding is implemented in Java ?

In order to avoid direct access of an attribute in a class, attributes are defined as private and use getter and setter methods to restrict the attributes access in a class. An example is given below
public class Person {
    private String FirstName;

    public String getFirstName() 
        return FirstName;
    public void setFirstName(String FirstName) 
        this.FirstName = FirstName;

46. What is a Constructor ?

The default constructor is called automatically, when an object of that class is created. A constructor has the same name as the that of the class.

A constructor always returns objects of the class, hence there is no return type specified in it's definition. A constructor is most often defined with the accessibility modifier “public” so that every program can create an instance but is not mandatory. A constructor is provided to initialize the instance variables in the class when it is called.

If no constructor is provided, a default constructor is used to create instances of the class. A default Constructor initializes the instance variables with default values of the data types. If at least one constructor is provided, the default constructor is not provided by the JVM. A class can have multiple constructors.

class Car {
String brand;
String color;
public Car() {
public Car(String b, String c, int w, int s, int g)
void accelerate(){}
void brake(){}

47. What is access modifier and what are it's types?

An attribute that determines whether a class member can be accessed or not. Different types of access modifiers are:
  • Public - Members are accessible to the class and to other classes.
  • Private - Members are accessible only to the class.
  • Protected - Members are accessible only to the class, it's subclass(es), and other classes in the package.
  • Default - Members are accessible only to the class and other classes within that package. This is the default access specifier.


48. What is final keyword?
If a variable is declared as final, it's value can't be modified. If a method is declared as final, it can't be overridden in the subclass. A class declared as final cannot be inherited.
49. What is static keyword?

We can define variables and methods of a class as "Static". If we declare a method or a variable as static, it means that the data member belongs to the class rather than any specific instance of a class. Static Methods and data members can be called without instantiating the class. A static member exists even if no objects of that class exist.

50. What is abstract keyword?

Abstract keyword is used to declare a class, when we want to expose certain functionality to the users and hide the underlying implementation. We can't create an instance of the abstract class. An abstract class can contain abstract and non-abstract methods.

51. What is synchronized keyword?

It controls the access to a block in a multithreaded environment.

52. What is native keyword?

Native keyword is used only with methods. It signals the compiler that the method has been coded in a language other than Java. It indicates that method lies outside the Java Runtime Environment.

53. What is a transient variable?

A transient variable is a variable that won't be serialized.i.e JVM understands that the transient variable is not part of the persistent state of the object. For example

class A implements Serializable {
transient int i; // will not persist
int j; // will persist

Here, if an object of type A is written to a persistent storage area, the contents of "i" would not be saved, but the contents of "j" would.

54. What is sctrictfp keyword?

The floating point precisions vary based on the platform on which Java program is run. In order to make sure that constant results are obtained while doing operations with floating point variables, Java provides "strictfp" keyword. If not at class class level , strictfp behavior can be applied at method level, by declaring a method as strictfp.

55. Explain method overriding with an example?

Method overriding is defined as creating a non-static method in the subclass that has the same return type and signature as a method defined in the superclass. The signature of a method includes the name of the method and number, sequence, type of arguments.

public class Person {
private String name;
private String ssn;
public void setName(String name) { = name;
public String getName() {
return name; }
public String getId() {
return ssn;}

getId method is overridden in subclass:

public class Employee extends Person
private String empId;
public void setId(String empId)
public String getId() {
return empId;

56. What is the use of super keyword. Give an example?
It allows you to access methods and properties of the parent class.

public class Person {
private String name;
public Person(String name) { = name; }
public String getName() {
return name;
} }
public class Employee extends Person {
private String empID;
public Employee(String name) {
super(name); // Calls Person constructor
public void setID(String empID){
public String getID(){
return empID;

57. What is an interface?

If we want enforce certain behaviour on objects implementing an interface, so that all the object provides certain functionalities irrespective of it's underlying implementation, we use Interface Class. The Interface is a conceptual entity. It can contain only final variables and abstract methods.

For example, you might specify Driver interface as part of a Vehicle object hierarchy. A human can be a Driver, but so can a Robot.

58. What is an abstract class?

  • An Abstract class is a conceptual class.
  • An Abstract class cannot be instantiated – objects cannot be created.
  • Abstract classes act as a base for a group of classes, which are closely related in a package.
  • If a class is declared as “final”, we can't extend that class. In some cases, properties of a class should be extended and used in sub-classes. Such classes are called Abstract Classes.


59. What are the properties of abstract class?
  • A class with one or more abstract methods is automatically abstract and it cannot be instantiated.
  • A class declared abstract, even with no abstract methods cannot be instantiated.
  • A subclass of an abstract class can be instantiated if it overrides all abstract methods by implementing them.
  • A subclass that does not implement all of the superclass abstract methods is it'self abstract; and it cannot be instantiated.
  • We cannot declare abstract constructor or abstract static methods.


60. What is object class in java?

Every class that we create extends the class Object by default. It means that the Object class is at the top of the hierarchy. Due to this default inheritance of object class, we can pass an object of any class as an argument to any method.

61. What are the methods of object class?

The methods in this class are:

  • equals(Object ref) - returns if both objects are equal
  • finalize( ) - method called when an object’s memory is destroyed
  • getClass( ) - returns class to which the object belongs
  • hashCode( ) - returns the hashcode of the class
  • notify( ) - method to give message to a synchronized methods
  • notifyAll( ) - method to give message to all synchronized methods
  • toString() - return the string equivalent of the object name
  • wait() - suspends a thread for a while
  • wait(...) - suspends a thread for specified time in seconds

62. What does java.util package provides?

The java.util package provides various utility classes and interfaces that support

  • Date & calendar operations
  • String manipulations
  • Collections Operations

63. How do we convert object to string?

For a reference type object, converting from object to string is done by calling "toString()" on the reference. All reference types inherit this method from java.lang.Object and override this method to produce a string that represents the data in a form suitable for printing.

In case of Java's primitive types, to make a conversion to a string, the compiler must wrap the primitive data type in it's wrapper class, and call the "toString()" method of the wrapper class.

String arg1 = new Integer(1 + 2).toString();

For user defined class, the standard Object.toString() produce something like "ClassName@123456" (where the number is the hashcode representation of the object). To have something meaningful, the classes have to provide a method with the signature public String toString().

public class Car() {
String toString()
return brand + ” : ” + color + ” : ”+wheels+” : “+ speed;

64. How can we convert string to object?

Many data type wrapper classes provide the valueOf(String Variable) method which converts the given string into a numeric value. The syntax is straightforward. It requires using the static Integer.valueOf(String s) and intValue() methods from the java.lang.Integer class.

To convert the String "22" into the int 22 you would write

int i = Integer.valueOf("22").intValue(); 
Doubles, floats and longs are converted similarly. To convert a String like "22" into the long value 22 you would write
long l = Long.valueOf("22").longValue();

To convert "22.5" into a float or a double you would write:

double x = Double.valueOf("22.5").doubleValue(); float y = Float.valueOf("22.5").floatValue(); 

If the passed value is non-numeric like “Four", it will throw a NumberFormatException.

65. What is Regular expression?

Regular expressions or Java Regex is an API to search or manipulate string based on a certain pattern. It is supported by the java.util.regex API, which provides one interface and three classes.

66. What does rejex package consists of?

The java.util.regex package primarily consists of three classes: Pattern, Matcher, and PatternSyntaxException. Let us see what each class does. To define a pattern for regex engine, Pattern class is used. An object of Pattern class is a compiled version of a regular expression. No constructors are provided by the Pattern class.
In order to create a pattern, a static method(Compile(expression)) of the pattern class is invoked, which accept a regular expression as the argument. The subsequent object returned by the pattern class is used for identifying a match.
Pattern s = Pattern.compile(".p">);// Checking single character
Matcher m = p.matcher("apple");

Job of the matcher object is to perform the match operation against an input, after interpreting the pattern. Like the Pattern class, Matcher objects are created by invoking the "matcher" method of a Pattern object. A PatternSyntaxException is used to throw an exception, if there is a syntax error in a regular expression pattern.

67. What is StringBuffer class is used for?
  • StringBuffer is used to create and manipulate strings, which undergoes frequent modifications.
  • If we define a StringBuffer without specifying the data it can hold, it will alocate 16 bytes. Advantage of the striger buffer is that, if more data is added to buffer than the alloted size, it's capacity will grow dynamically to handle additional characters. The operators + and += can't be used for string concatenation.
  • It has fewer utility methods (e.g. substring, trim, ....)
68. What is the difference between StringBuffer and StringBuilder class?

The StringBuffer class is not threadsafe whereas StringBuilder class is threadsafe. It means that the methods of the StringBuilder class are synchronized.

69. What is matcher in regex package?

A matcher is created from pattern object, by calling it's matcher method. A matcher is used to perform three different match operations, such as:

  • Matching a input sequence against a given pattern. 
  • Using "lookingAt()" method to match a sequence, from the start till it find a matching pattern. 
  • Using find() method to find all the matching sequences that matches the pattern, just like iterator

70. How to add comments in Java File ?

Comments can be inserted in 3 ways as shown below
// Comment Type1
/* Multi Line Comments
* Comment Line 2 */
/* Documentation Comment
* Comment Line 2 */ 
This comment will be added in the automatic document generation

Java Interview Questions on Collections

71. What are the limitations of array?

Arrays do not grow while applications demand. It has inadequate support for inserting, deleting, sorting, and searching operations.

72. What is collection framework?

Collections Framework provides a generic set of methods and interfaces inorder to handle collections. It can be summarized as

  • Interfaces that characterize common collection types 
  • Abstract Classes which can be used as a starting point for custom collections and which are extended by the JDK implementation classes. 
  • Classes which provide implementations of the Interfaces.
  • Algorithms that provide behaviors commonly required when using collections i.e. search, sort, iterate, etc.

To access each item of a collection, the framework provides Iterator interface. Advantage of the iterator interface is that it gives a well defined standard way to access the elements in a collection, one at a time.

73. What is set interface about?

The Set interface is used to represent a collection which does not contain duplicate elements. The Set interface extends the Collection interface. It stipulates that an instance of Set contains no duplicate elements.

The classes that implement Set must ensure that no duplicate elements can be added to the set. It means that the two elements, Obj1 and Obj2 can't be in a set if Obj1.equals(Obj2) is true.

74. What is HashSet, LinkedHashSet and TreeSet?

HashSet, TreeSet, and LinkedHashSet are the three general purpose implementations of the set interface provided by the Java platform.

  • HashSet: This is an unsorted, unordered Set. This may be chosen when order of the elements are not important.
  • LinkedHashSet: This is ordered. The elements are linked to one another(Double-Linked). This will maintain the list in the order in which they were inserted.
  • TreeSet: This is a sorted set. The elements in this will be in ascending order by default. You can also define a custom order using a Comparator passed as a parameter to the constructor.

75. Which one to choose and when among HashSet, LinkedHashSet and TreeSet?

  • HashSet is a good choice for representing sets if you don't care about the order of elements in a set. But if ordering is important, then LinkedHashSet or TreeSet are better choices. However, LinkedHashSet or TreeSet come with an additional speed and space cost.
  • Iteration over a LinkedHashSet is generally faster than iteration over a HashSet. 
  • Tree-based data structures get slower as the number of elements get larger. 
  • HashSet and LinkedHashSet do not represent their elements in sorted order.
  • TreeSet provides additional features such as finding the first and last elements in a set.

76. What is Enumeration interface?

The Enumeration interface helps us to loop through the objects of a collection. To check whether an element exists in a collection, interface provides hasMoreElements() method. It will return a boolean(true), if an element exists.

If "hasMoreElements()" returns true and we want to fetch the next object in the collection, use nextElement() method. In case there is not more objects exists in the collection and if we call nextElement() method, the runtime NoSuchElementException will be thrown.

77. Explain Iterator interface?
The Iterator is a special object to provide a way to access the elements of a collection sequentially. Iterator implements one of two interfaces: Iterator or ListIterator. An Iterator is similar to the Enumeration interface, Iterators differ from enumerations in two ways:
  • Iterators allow the programmer to remove elements of a collection during the iteration. Method names used by the iterator are shorter compared to Enumeration interface.
  • Method hasNext() of the Iterator interface returns true, if the iteration has more elements. To get the next object in the iteration, call next() Method. To remove the last element returned by the iterator, invoke remove() method which is optional.


78. What is SortedSet interface?

SortedSet extends Set interface, which make sure that the elements of a set is sorted. An example of a SortedSet interface is TreeSet. We can use iterator to fetch the sorted elements in the set.

79. How elements can be sorted in java collections?

The elements can be sorted in two ways. One way is to use the Comparable interface. Objects can be compared using the compareTo() method. This approach is referred to as a natural order.

The other way is to specify a comparator for the elements in the set if the class doesn't implement the Comparable interface, or you don’t want to use the compareTo() method in the class that implements the Comparable interface. This approach is referred to as order by comparator

80. What is a list interface?

  • The List interface allows us to create a list of elements. The List interface extends the Collection interface.
  • A list allows us to store duplicate elements in a collection. A list also allows to specify where the element is to be stored. The user can access the element by index. 

81. Compare ArrayList vs LinkedList?

  • ArrayList uses dynamic array to store the data, whereas the LinkedList uses a doubly linked list.
  • Data manipulation is faster with LinkedList compared to the ArrayList.
  • ArrayList can act only as a list, whereas the LinkedList can act as a list and a queue.

82. What is a vector class?

The Vector class is similar to ArrayList, when it comes to accessing the elements in a collection. Once an object of the vector is created, it's size can grow or shrink when we add or remove items in a Vector. It is synchronized by default.

83. What is a Stack class?

The Stack class represents a last-in-first-out (LIFO) stack of objects. The elements are accessed only from the top of the stack. You can retrieve, insert, or remove an element from the top of the stack.

84. What is a Map interface?

A Map is a storage that maps keys to values. Map doesn't support duplicate keys and each key maps to at most one value. The Map interface is not an extension of the Collection interface. Instead the interface starts off it's own interface hierarchy. The interface describes a mapping from keys to values, without duplicate keys. The keys are like indexes. In List, the indexes are integer. In Map, the keys can be any object.

85. Describe about HashMap and TreeMap?

The HashMap and TreeMap classes are two concrete implementations of the Map interface. Both will require key &value. Keys must be unique. The HashMap class is efficient for locating a value, inserting a mapping, and deleting a mapping. The TreeMap class, implementing SortedMap, is efficient for traversing the keys in a sorted order.

HashMap allows null as both keys and values. When it comes to speed, TreeMap is slower than HashMap. In TreeMap, an optional Comparator object is used to decide the order in which the keys are sorted.

86. What is the purpose of Collections class in util package?

The Collections class provides various methods to operate on collections and maps, synchronizing collection classes and making collection classes read-only.

87. How do we order/sort objects in collections?

To provide ordering/sorting of the objects, Java API provides two interfaces Comparable and Comparator

  • Comparable interface is in java.lang
  • Comparator interface is in java.util

88. When to use Comparable and Comparator in code?

The Comparable interface is simpler and less work

  • Your class implements Comparable
  • You provide a public int compareTo(Object o) method
  • No argument is passed to your TreeSet or TreeMap constructor
  • You will use the same comparison method every time

The Comparator interface is more flexible but slightly more work

  • We can create classes that implement Comparator as we wish
  • You can sort the TreeSet or TreeMap differently with each Comparator
  • TreeSet or TreeMap use the comparator in constructor as required. For example, sort Students by score or by name

Suppose you have students sorted by score, in a TreeSet you call studentsByScore. Now you want to sort them again, this time by name

Comparator<Student> myStudentNameComparator = new MyStudentNameComparator();
TreeSet studentsByName = new TreeSet(myStudentNameComparator);

89. What are the new features added in Java 1.5?

Generic classes
  • New approach to loops – Enhanced for loop
  • Static imports
  • Arrays, string builder, queues and overriding return type
  • Output formatting – format() and printf()
  • Autoboxing of primitive types
  • Enumerated types
  • Variable length of arguments


90. What is Generic classes?
Generic classes is one of the best features of Java 5. Since it is backward compatible with Java 1.4, old programs will work on latest Java. Le us have a look at the features ad use of generic Classes. it's quite common that Java throws ClassCastException at runtime, while working with collection classes. To avoid this nasty surprise, Java 5 had introduced compile-time type checking.
If we are using generic classes, we don't want to typecast while retrieving the items from the collections.
91. What is the big advantage of Generics?
Big advantage: collections are now type safe. For example, you can create a Stack that holds only Strings as follows:
Stack<String> names = new Stack<String>();
You can write methods that require a type-safe collection as follows:
void printNames(Stack<String> names) {
String nextName = names.pop(); // no casting needed!
names.push("Hello"); // works just the same as before
names.push(Color.RED); // compile-time error!


92. What is StringBuilder class?

Compared to StringBuffer, StringBuilder is an improved version to do similar tasks. It allows quick concatenation of strings. It is not safe for use by multiple threads at the same time since the methods are not synchronized.

Why use StringBuilder?

Creating new Strings in a loop can be inefficient because of the huge number of new objects that gets created and discarded.

StringBuilder.append(<type> <value>)
StringBuilder.insert(<type> <value>)

93. What is Queue interface?

  • Queue extends the Collection interface. The main objective of the queue is to hold elements that are to be processed later. Elements in a queue are typically ordered by First-In-First-Out(FIFO) order.
  • Main Methods provided by the queue are "remove()" and "pull()" method. Both the elements return the first element in the queue. if a queue is empty and if we invoke remove() method, Java throws an exception. In case of calling pull() method on an empty queue, null is returned.

94. Describe covariant return types with an example?

It allows the user to have a method in an inherited class with same signature as in the parent’s class but differing only in return types. It makes programs more readable and solves casting problems.

class Shape
public Shape transform(int x, int y)
class Rectangle extends Shape
public Rectangle transform(int x, int y)

95. What is boxing and unboxing ?

Converting a primitive data type like int, float, etc. to it's corresponding wrapper class object(Integer,Float etc.) is called boxing or autoboxing. Example of boxing,

int i = 0;
Integer O = new Integer(i);

Unboxing is the exact opposite of boxing where wrapper class object is converted into primitive data type. Example of unboxing,

i = O.intValue();

96. How autoboxing was done before java 5 and in java 5 version?

Before 5.0

ArrayList<Integer> list = new ArrayList<Integer>();list.add(0, new Integer(42)); int total = (list.get(0)).intValue();

From 5.0 version:

ArrayList<Integer> list = new ArrayList<Integer>();list.add(0, 42);int total = list.get(0);

97. How java distinguishes between primitive types and objects?

Java distinguishes between primitive types and Objects as follows.

  • Primitive types, i.e., int, double are compact, support arithmetic operators. 
  • Object classes(Integer, Double) have more methods. For example, Integer.toString()

You need a “wrapper” to use Object methods:

Integer ii = new Integer( i ); 

Similarly, you need to “unwrap” an Object to do primitive operation

int j = ii.intValue() * 7;

Java 1.5 makes this automatic:

ArrayList<Integer> list = new ArrayList<Integer>();
list.add(0, 42);
int total = list.get(0);

98. What is Enum?

An enumeration(enum) are a list of constants to represent a predefined list of values. Before Java 5, enums are declared as follows.

public final int SPRING = 0;
public final int SUMMER = 1;
public final int FALL = 2;
public final int WINTER = 3;

This is a nuisance, and is error prone as well. Here’s the new way of doing it,

enum Season { winter, spring, summer, fall }

Enums are classes which extends java.lang.Enum.Enums. This interface is final and it can’t be subclassed. It provides only one Constructor and it is protected. It implements java.lang.Comparable: compareTo() and implements Serializable.

Java Interview Questions on Exceptions

99. What is an exception?

An exception can be defined as an event which disrupts the program execution flow.

100. What are the uses of exceptions?

  • Consistent error reporting style.
  • Easy to pass errors up the stack.
  • Pinpoint errors better in stack trace.
  • As long as you “fail fast” and throw as soon as you find a problem.
  • Wrap useful information on your exception classes and use that information later, while handling the exception.
  • Exceptions don’t always have to be errors, maybe your program can cope with the exception and keep going.
  • Separating error handling code from Regular code


101. What are the types of error?
There are two types of error:
  • Compile time error
  • Run time error
102. List some exception occurence reason?
Running out of memory, Resource allocation errors, Inability to find files, Problem in network connectivity, etc.


103. What are checked exceptions?

Checked exceptions are the type exceptions which are checked during compilation. A method which throws a checked exception, should advertise the exception in it's method definition. The method which calls another method that advertises a checked exception can handle it in two ways. One option is to handle the thrown exception in a try and catch block or it should advertise the exception thrown by calling method.

104. What are unchecked exceptions?

Exceptions raised implicitly by the system due to illegal code execution are called unchecked exceptions. We don't want to announce the possibility of exception occurrence. When the unchecked exception occurs, and the program is not written to handle it, it would be processed by the default exception handler.

105. How exception handling is implemented using try and catch statement?

The try block encloses a piece of code that may create an exception. It also acts as the scope of the associated catch block which handles exceptions.

106. What is throwing an exception?

The throw statement causes the termination of the normal flow of control of the Java code and stops the execution of the subsequent statements if an exception is thrown.

The throw clause transfers the control to the nearest catch block handling the type of exception object throws. The following syntax shows how to declare the throw statement:

public double divide(int dividend, int divisor) throws ArithmeticException {
if(divisor == 0) {
throw new ArithmeticException(“Divide by 0 error”);
return dividend / divisor;

107. When should we use throws exceptions?

The throws statement is used by a method to specify the types of exceptions the method throws. If a method is capable of raising an exception that it can't handle, the method must specify that the exception has to be handled by the calling method. This is done using the throws statement.

Example: void readData() throws IOException

108. How can we create our own exceptions?

Defining our own exceptions helps us handle specific exceptions that are tailor-made for our application. Steps to Create a User Defined Exception are:

Create a class that extend from a right kind of class from the Exception Hierarchy. For Example,

public class DivideByZeroException extends ArithmeticException 
public DivideByZeroException()
super("Divide by 0 error");

109. What are the exception occurrence levels?

Hardware/operating system level :

  • Arithmetic exceptions; divide by 0, under/overflow.
  • Memory access violations; segment fault, stack over/underflow.

Language level :

  • Type conversion; illegal values, improper casts.
  • Bounds violations; illegal array indices.
  • Bad references; null pointers.

Program level :

  • User defined exceptions.

110. What are the categories of exceptions?

There are two categories of exceptions:

  • Built in Exceptions
    • Checked Exceptions
    • Unchecked Exceptions
  • User Defined Exceptions

111. What is the use of finally clause?

The finally block is used to process certain statements, no matter whether an exception is raised or not. Generally, we write resource cleaning operations inside finally block. Like, closing a Java Inputstream.

112. What is an assertion?

An assertion is a statement which is used to test a program based on certain assumptions. The boolean expression inside assertion is supposed to return during execution. If the expression fails, Java will throw an AssertionError.

Assertions help programmers to identify and correct bugs faster. It is one of the efficient ways to detect bugs. Assertions can be used for internal documentation, which enhances code maintainability.

113. What are the different forms of assertion statements?
The assertion statement has two forms.
assert Expression1 ;
Where Expression1 is a boolean expression. When the system runs the assertion, it evaluates Expression1 and if it is false throws an AssertionError with no detail message.
assert Expression1 : Expression2 ;

Where Expression1 is a boolean expression and Expression2 is an expression that has a value. This form of assert statement provides a detail message for the AssertionError.

114. How do we enable and disable assertions?

To enable assertions use -enableassertions, or -ea, option at runtime. To disable assertions use -disableassertions, or -da. Specify the granularity with the arguments provided at runtime.

  • no arguments - Enables or disables assertions in all classes except system classes. 
  • packageName - Enables or disables assertions in the named package and any subpackages. 
  • "-" Enables or disables assertions in the unnamed package in the current working directory. 
  • className - Enables or disables assertions in the named class

Java I/O Interview Questions

115. What are the basic functionalities provided by io package?

Many Java programs need to read or write data to an external source. Read/Write operations are carried out by classes in package. A program can get input from a data source by reading a sequence of characters from an InputStream attached to the source. A program can produce output by writing a sequence of characters to an OutputStream attached to a destination.

116. What is a Stream?

A stream is a flowing set of data. Streams support different types of data, such as bytes, objects, data types, etc. Streams can be used for simple data transfer, data manipulation or data transformation. We can use an input stream to read data from a source, one at a time and we can write data to the target, one at a time.

117. What is an inputstream?

The class is a superclass which provides an interface and a partial implementation to all input streams. The InputStream class defines methods for reading bytes or arrays of bytes.

118. What is a FileInputStream?

It reads data from a file on the native file system. For example, reading raw bytes of data from an image file.

119. What is ByteArrayInputStream?

A ByteArrayInputStream contains an internal buffer which is used to store the bytes that are read from a stream. ByteArrayInputStream keeps track of the byte that needs to supplied during the next read operation.

120. What is SequenceInputStream, StringBufferInputStream, PipedInputStream?

  • SequenceInputStream : It concatenates multiple input streams into one input stream. 
  • StringBufferInputStream : It allows programs to read from a StringBuffer as if it were an input stream. 
  • PipedInputStream : In this data can be read from a thread by using PipedInputStream

121. What is FilterInputStream?

FilterInputStream is a subclass of InputStream. FilterInputStream class provides interfaces to process/filter data while the data is read or written to and from a stream.

122. What is BufferedInputStream?

BufferedInputStream is used to buffer input streams. When we create a Buffered Input Stream, an internal array will be created. Advantage of Buffered Stream is that it reads large blocks of data at a time and store it into it's internal buffer. This process is much faster compared to reading a byte at a time.

123. What is an Enumeration interface and what are it's methods?

The Enumeration interface is used to fetch items from a collection of objects, one at a time. To check whether the elements exist in a collection, hasMoreElements() method is used. The method returns true if items exist in the collection. To fetch the next item in the collection, use nextElement() method. If no more items exists in the collection and if nextElement() is called, the NoSuchElementException will be thrown.

124. What is a DataInputStream?

A DataInputStream helps application read primitive data types from an input stream. It reads the data types irrespective of the underlying OS on which it is run. It is not thread safe.

125. What is an OutputStream?

The OutputStream is used to write bytes or an array of bytes to a stream. The OutputStream is an abstract class, which provides an interface and implementations of the output stream.

126. What is a FileOutputStream?

A FileOutputStream is used to write data to a file. While writing data, if the file is not available, it will be created by the stream.

127. What is a ByteArrayOutputStream and FilterOutputStream?

ByteArrayOutputStream writes data into a byte array. The byte array will then be written to multiple streams. FilterOutputStream class is used to filter various output streams.
128. What is BufferedOutputStream and PrintStream?

A BufferedOutputStream avoids multiple write to a stream by initially writing the data to a buffer. When the buffer is full/flushed, the data is written to the actual stream. A PrintStream class helps us to write data to another output stream. It can format primitive data types like int, long etc. and write as text to any OutputStream.

129. What is object serialization?
Serializing objects is the process of writing objects to a file. When an object is serialized, it's state and other attributes are converted into an ordered series of bytes. This byte series can be written into streams.

130. Why should we use object serialization?

Object serialization takes an object's state, and converts it to a stream of data. With object serialization, it's very easy to make any object persistent, without writing custom code to save object member variables.
131. How to prevent writing some member data value during object serialization?

The transient keyword is used to indicate the JVM that the variables that are marked as transient in an object is not part of the persistent state of the object and it should be excluded while saving the object.

132. What are Reader and Writer classes?
Reading and writing character streams are handled by Reader and Writer classes. These classes are abstractions that Java provides for dealing with reading and writing character data.
133. Give few examples of simple Reader and Writer classes?
  • FileReader and FileWriter : Read data from or write data to a file on the native file system.
  • PipedReader and PipedWriter : They are used to channel the output of a program or thread into the input of another program or thread. 
  • CharArrayReader and CharArrayWriter : Read data from or write data to a char array in memory.


134. What are FilterReader/FilterWriter, BufferedReader/BufferedWriter and PrintWriter?

  • FilterReader and FilterWriters are subclasses of Reader and Writer, respectively. These classes define the interface for filtered streams which process data as it's being read or written.
  • BufferedReader and BufferedWriter : They buffer data while reading or writing, in order to reduce the number of read/write access on the original data source.
  • PrintWriter : An output stream with convenient print methods

135. What is a File class?

It represents a file on the native file system. We can create a File object for each file in the file system, so that we fetch the information about the file from the object. For example, Name, Full pathname etc.

136. What are the functionalaties we get using File class?

The File class in the package provides various methods to access the properties of a file or a directory, such as file permissions, date and time of creation, and path of a directory.

Java Interview Questions on Threads

137. What are the benefit's of using threads in an application?

  • It improves performance .
  • It minimizes system resource usage. 
  • We can access multiple applications simultaneously. 
  • Threads simplifies the program structure.
  • We can send & receive data on the network at the same time.
  • We can read & write files to disk simultaneously.

138. What are the differences between process and threads?


It is an executable program loaded in the memory. It has its own address space – variables & data structures (in memory). Process communicates via the operating system, files, network. A process may contain multiple threads.


It is sequentially executed stream of instructions. It shares an address space with other threads and it has it's own execution context.

139. What are the types of thread?

There are two types of thread:

  • Single Threaded Process
  • Multi Threaded Process

140. What is single threaded and multi threaded process?

  • Single Threaded Process: A thread is defined as the independent path of execution within a program. A process that is made of one thread is known as single-threaded process.
  • Multi Threaded Process: A process that creates two or more threads is called a multithreaded process.

141. What is the basic concept of multitasking and it's types?

Multitasking is the ability to execute more than one task at the same time. Multitasking can be divided into two categories:
  • Process based multitasking
  • Thread based multitasking


142. Give example and describe process and thread based multitasking?
When we work with two different programs simultaneously, it is known as Process based multitasking. For example, listening to a music and working with MS-Excel.
When a program executes various tasks within simultaneously, it is known as Thread based multitasking. For example, MS-Word can do spell check and count the number of lines while we work on a document.
143. What are the disadvantages of multitasking?
  • Race condition
  • Deadlock condition
  • Lock starvation


144. How to use threads in java?

By using Thread class, Java.lang.Thread class is used to construct and access individual thread in a multi threaded application.

145. What are the stages of Thread Lifecycle?

  • New : It is created by instantiating the Thread class. Thread th = new Thread(this);
  • Runnable: By calling the start method that in turn call run method. th.start();
  • Not Runnable: Calling wait or sleep method or caused due to io interrupts. wait(); th.sleep(1000);
  • Dead or terminate: After run() method completes execution.

146. What are the two ways of creating threads in java?

Two ways of creating Thread in Java:

  • Extending from java.lang.Thread class
  • Implementing the Runnable Interface

147. Which is the first thread to be executed in a multithreaded process?

The first thread to be executed in a multi-threaded process is called the main thread. The main thread is created automatically on the startup of Java program execution.

148. What is thread scheduling and what does it determines?

The scheduling can be described as the management of execution of various threads on a single CPU.

  • It determines which runnable threads to run
  • It can be based on thread priority
  • It is part of OS or Java Virtual Machine (JVM)

149. What thread scheduling does java runtime supports?

The Java runtime supports fixed priority scheduling algorithm, which is simple and deterministic.

150. Describe thread policy in java?

  • Thread priorities are the integers in the range of 1 to 10 that specify the priority of one thread with respect to the priority of another thread.
  • Each Java thread is allocated with a priority number ranging between MIN_PRIORITY and MAX_PRIORITY.
  • The JRE chooses the runnable thread with the maximum priority of execution, when it had to choose from a range of threads which are ready to execute.
  • The Java Run-time Environment executes threads based on their priority.
  • A thread with higher priority runs before threads with low priority. 
  • At any moment of time, a given thread may give up its right to execute by calling the yield method.
  • You can set the thread priority after it is created using the setPriority() method declared in the Thread class.

151. What is synchronization?

Synchronization of threads makes sure that a shared resource can be accessed by only one thread at a time, even if multiple threads what to access the shared resource at any given moment of time.

152. Why synchronization is required?

  • Problem: Race condition! Two or more threads want to access the same object and each thread want to modify the state of the object. 
  • Result: Corrupted object. The solution to this is synchronization.

153. What is monitor?

A monitor is an object that can block threads and notify them when it is available.The monitor controls the way in which synchronized method's access an object or class. To enter an object’s monitor, you need to call a synchronized method.

154. How to acheive synchronization in java?

Synchronization can be achieved in Java using synchronized keyword.

155. What are the two levels of acheiving synchronization?

  • Method level
  • Block level
156. What is inter thread communication?

A thread may notify another thread that the task has been completed. This communication between threads is known as interthread communication.

157. What are the various methods used in inter thread communication?
The various methods used in interthread communication are:
  • wait()
  • notify()
  • notifyAll()
158. How JDBC architecture can be categorized?
JDBC architecture can be categorized into two layers:
  • JDBC Application layer
  • JDBC Driver layer


159. In which package jdbc api classes and interfaces are available?

The JDBC API classes and interfaces are available in the java.sql and the javax.sql packages.

160. What are the commonly used classes and interfaces in JDBC api?

The commonly used classes and interfaces in the JDBC API are:

  • DriverManager class: Loads the driver for a database. 
  • Driver interface: Represents a database driver. All JDBC driver classes must implement the Driver interface. 
  • Connection interface: Enables you to establish a connection between a Java application and a database. 
  • Statement interface: Enables you to execute SQL statements. 
  • ResultSet interface: Represents the information retrieved from a database. 
  • SQLException class: Provides information about the exceptions that occur while interacting with databases.

161. What are the steps to create JDBC application?

  • Load a driver
  • Connect to a database
  • Create and execute sql statements
  • Handle exceptions

162. How do we load a driver in jdbc?

Loading a Driver can be done in two ways:


  • Using the forName() method
  • Using the registerDriver()method


  • By setting system property

163. How do we load driver programmatically?

Using the forName() method

  • The forName() method is available in the java.lang.Class class.
  • The forName() method loads the JDBC driver and registers the driver with the driver manager. 
  • The method call to use the the forName() method is:
  • Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

Using the registerDriver() method

  • You can create an instance of the Driver class to load a JDBC driver. This instance provide the name of the driver class at run time. The statement to create an instance of the Driver class is:
Driver d = new sun.jdbc.odbc.JdbcOdbcDriver();

You need to call the registerDriver() method to register the Driver object with the DriverManager. The method call to register the JDBC-ODBC Bridge driver is:


164. How we connect to a database in JDBC?

Connecting to a Database Using DriverManager.getConnection() method:
Connection getConnection (String <url>)
Connection getConnection (String <url>, String <username>, String <password>)
Connects to given JDBC URL.
throws java.sql.SQLException
Returns a connection object.


Connection con=DriverManager.getConnection(“jdbc:odbc:MyDSN”,”scott”,”tiger”);

165. What are the different types of statements in JDBC?

  • Statement Interface : A Statement object is used for executing a static SQL statement and obtaining the results produced by it.
  • Statement createStatement() : returns a new Statement object.
  • Prepared Statement Interface: When you use a PreparedStatement object to execute a SQL statement, the statement is parsed and compiled by the database, and then placed in a statement cache. From then on, each time when you execute the same PreparedStatement, it is once again parsed, but no recompile occurs. Instead, the precompiled statement is found in the cache and is reused.
  • PreparedStatement prepareStatement(String sql) : returns a new PreparedStatement object.
  • CallableStatement Interface : The interface used to execute SQL stored procedures.

166. What is a ResultSet interface?

A ResultSet provides access to a set of data generated by executing SQL query. We can open only one ResultSet per Statement. We can access only one row at a time in sequence.

Popular Videos


How to improve your Interview, Salary Negotiation, Communication & Presentation Skills.

Got a tip or Question?
Let us know

Related Articles

Java OOPS Interview Questions and Answers
Top Advanced Java Interview Questions and Answers
Java Collections Interview Questions and Answers
Java Thread Interview Questions and Answers