Top 30 Java Interview Questions and Answers

1. What is the difference between HashMap and Hashtable in Java?

Ans.

S.No. HashMap Hashtable
1. HashMap is neither synchronized nor thread-safe. Hashtable is synchronized as well as a thread-safe.
2. It allows only one NULL key and any number of NULL values. It does not allow any NULL key and value.
3. It is not a legacy class. It is a legacy class.
4. It extends the AbstractMap class. It extends the Dictionary class.
5. HashMap returns only the Iterators for traversing the elements. The Hashtable returns both iterators and the Enumeration.
6. HashMap returns only the Iterators which are fail-fast in nature. Hashtable returns the Enumerations which are fail-safe in nature.
7.   It is fast. It is slow because it is internally synchronized.

 2. Write a program of HashMap in Java?

Ans.

Output of Program

program of HashMap in Java

3. Explain the difference between Enumeration and Iterator in Java?

Ans.

S.No. Enumeration Iterator
1. Enumeration is introduced in JDK 1.0 version. Iterator is introduced in JDK 1.2 version.
2. Enumeration has the methods only for traversing the elements, not for the modification of collection. Iterator can also remove elements while traversing the collection by using the remove() method.
3. Methods in Enumeration hasMoreElements(); nextElements();   Methods in Iterator hasNext(); next(); remove();
4. It is applicable to the legacy class such as vector. It is applicable to all the collection classes.
5. We can create the object of an Enumeration like this: Enumeration t = vt.elements(); We can create the object of an iterator like this: Iterator it = c.iterator();  
6. Enumeration is fail-safe (safe and secure) in nature. Iterator is fail-fast in nature.
7. By calling the element() method of vector class, we create an object of it. By calling the iterator() method present in the collection interface, we can create an object or iterator.

4. Explain the difference between Set and List in Java?

Ans.

S.no List Set
1. It is a sequence of characters which stored elements in an ordered way. It is a list of elements which stored elements in the shuffle or unordered way.
2. There can be duplicate values in a list. Set does not allow duplicate value, if the duplicate value is to be inserted to a list, it gets overwritten.
3. The list can have more than one NULL value in its collection. Set can have only one NULL value in its collection.
4. In Java, implementation of List interface are ArrayList, vector class and LinkedList class. In Java, implementation of a set interface are TreeSet, HashSet, LinkedHashSet.
5. The List never maintains the order of insertion. Set always maintains the insertion order.
6. The List uses the various methods such as add(), addAll(), get(), ListIterator() with or without parameter, lastIndexOf(), remove(), set(), and subList(). Set uses the methods such as clear(), add(), contains(), isEmpty(), size() and remove().


7. List has one legacy class called as a vector. There is no legacy class in the set interface.
8. Methods available in List: Iterator() ListIterator() Methods available in set: Iterator()  

5. What is Serialization in Java?

Ans. In Java, it is a mechanism of converting the state of an object into a stream of bytes so that it can be saved as a file, stored in a database or transported to other platforms through a network. This process is also known as marshalling.

A class must implement a java.io.Serializable interface to serialize its object successfully. For Serializing the object, we call the method writeObject() of java.io.ObjectOutputStream Class.

Serializable interface is a marker interface that does not provide any filed or method to implement.

6. What is Deserialization in Java?

Ans. In Java, it is a process of converting the byte stream into an object. It is the reverse process of serialization.

For Deserialization, we call the method readObject() of java.io.ObjectInputStream Class.

7. What is JIT compiler?

Ans. It stands for just-in-time compiler. It is a component of Java Runtime Environment. Jit is a compiler that improves the performance of application written in Java by compiling bytecodes to the native machine codes at execution time.

8. Explain the difference between abstract class and interface?

Ans.

S.no               Abstract Class Interface
 1 An abstract class can contain abstract, non- abstract methods, or both. An interface contains only static constants and abstract methods.
2  Except private, we can use any access specifier for the methods in an abstract class. All the methods declared in the interface must be public access specifier.
3   An abstract class can use any access specifier except private. All the variables defined in an interface must be static, final, or public.
4  Multiple inheritance cannot achieve using an abstract class. Multiple inheritance can be reached by an interface.
5  ‘Abstract’ keyword is used to declare the abstract class. Specify the ‘Interface’ keyword before the class name to declare the interface.
6 An abstract class can have a constructor.   The interface does not have a constructor.
 7 A subclass in Java can extend only one abstract class. The interface implements multiple interfaces.
8  These classes implement interfaces and extend other classes. An interface can extend only other interfaces.
9  We can execute an abstract class if it has a main() method. We cannot execute interface because they cannot have a main() method.

9. What is an Exception in Java and explain its types?

Ans. Exception: An exception is an unexpected error or event which occurs during the execution of the Java program that disrupts the normal flow of instruction in a program.

There are some situations where an exception occurs:

  • When the user entered invalid data in the program.
  • File to be accessed not found in the system.
  • The network lost in the middle of communication.
  • JVM (Java Virtual Machine) has run out of memory.

An Exception is of two types:

  1. Checked Exception
  2. Unchecked Exception

Checked Exception: These exceptions are also known as compile-time exceptions. Checked exceptions are those exceptions that are checked by the compiler during the process of compilation to check whether the exception is handled by the coder (programmer) or not.

Example of Checked exception are:

IOExceptionSQLExceptionClassNotFoundException, and  InvocationTargetException

Unchecked Exception: These exceptions are also known as the Run time exceptions. Unchecked exceptions are those exceptions that occur during the program execution. These exceptions not checked at the compilation process.

Example of Unchecked exception are: programming bugs like logical errors, and using incorrect APIs.

10. Explain the difference between throw and throws?

Ans.

S. No. Throw Throws
1. In Java this keyword is used to throw an exception explicitly. In Java this keyword is used to declare an exception.
2. The throw keyword is followed by an instance of the exception. The throws keyword is followed by a class name.
3. It is used inside the method body. It is used with the method or function signature.
4. This keyword used to propagate the unchecked option that are not checked using ‘throws’ keyword. This keyword is primarily used to handle the checked exceptions.
5. It is used to throw only one exception at a time. This keyword declares multiple exceptions separated by ‘,’ commas.
6. This statement will create an exception object. Throws statement does not create any exception object.
7. Using this keyword, we can also break a loop or a switch statement without using the break. Using this keyword, we cannot perform any break in a loop or a switch statement.
8 Syntax: throw Throwable-instance;

Syntax: return_type method_name (parameter-list) throws ExceptionClass_list
{
// body of method
}
 

11. Write a program of using throw and throws keyword?

Ans.

Program of using throw keyword

Program of using throws keyword

12. What is the difference between finally, final, and finalize?

Ans. Final: In Java, it is an ‘access modifier’ or ‘keyword’ which is applied to a method, or a class or variable.

The class declared as a final cannot be inherited, a final method cannot be overridden, and the variable declared as a final cannot be changed.

This method is executed upon its call.

Finally: In Java, it is a block.

It is an exception handling code section which gets executed when an error or an exception is raised in a program.

This method is run after the execution of ‘try-catch’ block.

Finalize: In java, it is a method.

It is a protected method defined in the object class. This method is called by the garbage collector and executes before the destruction of the objects.

13. What is ClassLoader in Java?

Ans. The Java classLoader is a part of (JRE) Java Runtime Environment that dynamically loads the classes of Java into the Java virtual machine (JVM). 

In Java, classLoader works on three principles: delegation, uniqueness, and visibility.

In Java, classLoader is of three types

  • BootStrap classLoader
  • Extension classLoader
  • System classLoader

14. What is the difference between LinkedList and ArrayList in Java?

Ans.

  ArrayList LinkedList
1. It is an index based data structure. It is doubly linked list based data structure.
2. It allows random access to the elements in the list. It does not allow random access to the elements in the list.
3. It uses the dynamic array as internally to store the elements in the list. It uses doubly linked list as internally to store the elements in the list.
4.   In an ArrayList, access to the elements is faster. In a LinkedList, access to the elements is slower.
5. In an ArrayList, manipulation to the elements is slower. In a LinkedList, manipulation to the elements is faster.
6. It extends AbstractList class and implements List interface. It extends AbstractSequentialList class and implements List, Queue, and Dequeue interface.
7. Three constructors in ArrayList class: ArrayList( ) ArrayList(Collection<?extends E> c) ArrayList(int capacity) Two constructor in LinkedList class: LinkedList( ) LinkedList(Collection<? extends E> c)  
8. ArrayList does not allow reverse traverse of elements. LinkedList allow reverse traversal of elements.
9. The syntax for creating the ArrayList: List <string> arrayListname = new ArrayList <string> (); The syntax for creating the LinkedList: List <string> LinkedListname = new LinkedList <string> ();      

15. What is a thread in Java?

Ans.  All the programs of Java have at least one thread [ main() thread ], which is created by the JVM at the start-up of the program.

java.lang.Thread Class in Java creates and controls every thread. Thread is a facility to allow multiple activities within a single process. Each thread in Java has its own stack, program counter, and local variables.

In Java, thread implementation can be achieved in two ways

  1. By extending the thread class.
  2. By implementing the Runnable interface.

16. Describe the Life cycle of thread?

Ans. In Java, a thread consists of following states during its life cycle:

  1. New state: In this state, an instance of a thread is created. A thread remains in this state until the program invokes the start() method.
  2. Runnable state: After the calling of start() method, the thread moves from new to runnable state. A thread in this state is ready to run, but will not execute its task until the thread scheduler (which is a part of Java Virtual Machine) has not selected it to run.
  3. Running state: When the thread scheduler has selected thread to execute its task, then it is in running state.
  4. Blocked/Waiting/Sleeping state: A thread will be in the blocked state when it wants to execute some code of section but some other thread acquires that.
  5. Terminated or Dead state: A thread is in a terminated or dead state when the code of thread has executed completely by the program, or an unexpected error occurred in the execution of the thread.

17. What is the difference between string, StringBuilder, and StringBuffer?

Ans. String: In Java, It is basically an object which represents the immutable (not modifiable objects) sequence of char values.

We can create an object of a string by using the java.lang.String class. This class provides many useful methods to perform various operations on the string such as concat(), length(), replace(), equals(), substring(), toLowerCase(), trim(), etc. 

StringBuilder: java.lang.StringBuilder class provides an alternate to java.lang.String Class and represents a mutable sequence of characters. It is not synchronized, which means it is not a thread-safe. This class provides an API similar to the StringBuffer class.

The syntax for defining the StringBuilder class

public final class StringBuilder

extends Object

implements Serializable, CharSequence

StringBuffer: java.lang.StringBuffer class also represents the mutable sequence of characters. This class is introduced in Java 1.2 version.

This class is synchronized. Java.lang.StringBuffer class inherit from the object class.

The syntax for defining the StringBuffer class

18. What is the difference between this and super keyword in Java?

Ans. The super keyword is used to call the constructor of a base class, whereas this keyword is used to call the constructor of the current class.

Super is used to access the methods and variables of a base class, whereas this is used to access the methods and variables of the current class.

19. What is Java Applet?

Ans.  An applet is a small application of java that can be accessed on the internet server and can be automatically installed and execute as a part of a web document.

In Java, an applet is a class that extends the java.applet.Applet class.

Java Virtual Machine creates an instance of an applet class and invokes init() method to start an applet.

Applets can be executed by the different browsers in multiple platforms such as Linux, Windows, and Mac. They can be used to capable of performing various tasks such as display graphics, create animated graphics, play sound, etc.

Applets in java are compiled using the Javac command but run only with a browser or using the appletviewer command.

20. Explain the difference between an applet and a standalone application?

Ans.

s.no Java Applet Java Application
1. An applet is a program of Java which loads from the web server and executes by the web browser. A Java application is a standalone program which can be run independently on client or server without using the web browser.
2. In Java, applets are created by extends the java.applet.Applet class in a program Java applications are created by writing the code or program inside the main method.
3. Applets do not have access to read and write files on a local computer. Java applications have full access to read and write local files on a computer.
4. It requires the Java-compatible web browser for its successful execution. It requires the JRE (a combination of JVM and java class libraries) for its execution.
5. An applet in Java is compiled by using the javac command but run by using the appletviewer command. An application in Java is compiled by using the javac command and run by using the java command.
6. An applet in Java is initiated through the init() method. An application in Java is executed through the main() method.
7. An applet must run with the Graphical User Interface (GUI). Applications do not require any GUI.

21. Why main() method declared as a static?

Ans. In Java, the main() method is the standard method which is used by the JVM to start the execution of any program of Java. It is declared as static because it can be called without creating an instance of the class.

If we do not declare the main() method as static, program compile but not execute and interpreter shows this error:

main() method declared as a static

22. What is a package?

Ans. In Java, the package is a mechanism that encapsulates a group of classes, interfaces, and sub-packages. We have two type of packages, built-in packages, and user-defined packages.

The packages of Java provides access control to the classes. Packages can be stored in the compressed files called ‘jar’ files.

Suppose, if we want to give input at run time, we need to import this package in our program:

import java.util.Scanner

23. What is wrapper classes in Java?

Ans. Wrapper classes are the classes used for converting the primitive data types (byte, int, short, float, long, double, char and Boolean) into objects. All the wrapper classes in Java are subclasses of the class Number (abstract).

The following table shows the primitive data types and their matching wrapper classes

Primitive Datatypes Wrapper Class
Char Character
Int Integer
Float Float
Boolean Boolean
Byte Byte
Short Short
Double Double
Long Long

Take an example to understand the conversion of primitive data type to the corresponding object

24. Explain the difference between compile-time polymorphism and runtime polymorphism in Java?

Ans.

Compile-time polymorphism:

A Polymorphism that is resolved during compile-time and also known as static polymorphism.

In Java, this type of polymorphism achieves by using the method overloading.

Method overloading is nothing but declaring two or more methods with the same name in the same class, but they differ in number and types of parameters.

Runtime polymorphism:

A Polymorphism that are resolved during run time and also known as the dynamic polymorphism.

Run time Polymorphism is achieved by the method overriding.

25. What do you mean by constructor in java?

Ans. When a new object created for any class in a program, a constructor gets automatically called for that class. It is a method which has a name same as a class name and does not have a return type.
There are three types of constructor:

a)    Default constructor: If there is no implementation of constructor in a class, it is implicitly called in a class by the java compiler.

b)    Non-parameterized constructor: Constructor without the parameters or arguments.

 c)   Parameterized constructor: Constructor with arguments.

Example of constructor:

26. Explain the constructor overloading in Java with an example?

Ans. In Java, Constructor overloading is a technique of having more than one constructor with different parameter list inside one class, and it is similar to the compile-time polymorphism in Java.

Example:

27. What are the features of Java?

Ans. Features of Java are as follows:

  • Simple.
  • Secure.
  • Platform Independent.
  • Object-Oriented programming language.
  • Robust.
  • Portable.
  • Multithreaded and interactive.
  • High Performance.
  • Distributed.
  • Architectural-Neutral.
  • Interpreted.
  • Dynamic.

28. What are the local, static, and instance variable in java?

Ans. Local Variable:

  • Those variables which are defined or declared within a method or block or a constructor. These variables are created when any function or block starts its execution, and it will destroy after the function or block exits.
  • The scope of the local variable exists within a function body in which the variable is declared or defined. We cannot define local variables with the ‘static’ keyword.   

Instance variable:

  • Those non-static variables which are declared inside a class, but outside a method or a constructor are called instance variables.
    • Local variables are created when an object of a class is created, and it will destroy when an object is destroyed.
    • We may also be declared access specifier with the instance variables. If we don’t specify any access specifier with these variables, then default access specifier will use.
    • We can access instance variables by creating the object, and the initialization of these variables is not mandatory. Instance variable has its default value, for numbers – 0, and the Booleans – False.

Class/Static variable:

  • These variable are also known as class variables.
    •  Static variables are declared similarly as the instance variable but with the static keyword.
    • A single copy of the static variable is shared among all the object of a class. If there is a change in the value of the static variable, it is reflected in every object.
    • These variables are created when the program starts its execution and destroys when the program stops its execution.

29. What is the interface?

Ans.

  • Java uses the interface to achieve multiple inheritance or abstraction. The interface is like a class in Java, but the methods declared in an interface are by default abstract, i.e., methods don’t have a body, only method signature.
  • Along with the abstract method, it may also contain default methods, static constants, and static methods. 
  • Interface declared by specifying an ‘interface’ keyword before the class name.
  • In Java, a class that implements an interface should provide an implementation for all the abstract methods declared in the interface.
  • In an interface, methods are declared by default abstract and public. 
  • All the variables declared in it are public, static, and final by default.

30. What is Java compiler and interpreter?

Ans. Java Compiler: For Java programs, we can use any text editor like notepad, word pad, etc. for writing the source code and then saving that program with .java extension. Java compiler compiles that program on a terminal in Linux or Command prompt in Windows by using the syntax as given below and convert the source code into the byte code.

Syntax:

Java Interpreter: Java Interpreter converts the byte code into the machine code, i.e., Java Virtual Machine. It is a software that implements the JVM (Java Virtual Machine) and executes Java applications.

Syntax: