DEV Community

Vijay Singh Khatri
Vijay Singh Khatri

Posted on • Edited on

Top 20+ Java Interview Questions

It’s a no-brainer that Java is one of the leading programming options for bagging a lucrative job. After all, the class-based, general-purpose, object-oriented, programming language, is one of the most widely used programming languages in the world.

With a plethora of great features, the programming language is preferred not only by the seasoned experts but also pursued by those new to the programming world. So, here are 28 important interview questions that will help you bag a Java job, or, at the very least, enhance your learning.

Q: How will you differentiate HashMap from HashTable?
A:
HashMap in Java is a Map-based collection class, used for storing key & value pairs. It is denoted as:

HashMap or HashMap

HashTable is an array of a list, where each list is called a bucket. Values contained in a HashTable are unique and depend on the key.

Methods are not synchronized in HashMap while key methods are synchronized in HashTable. However, HashMap doesn’t have thread safety while HashTable has the same. For iterating values, HashMap uses iterator and HashTable uses enumerator.

HashTable doesn’t allow anything that is null while HashMap allows one null key and several null values. In terms of performance, HashTable is slow. Comparatively, HashMap is faster.

Q: What do you mean by Collections in Java? What are the constituents of Collections in Java?
A:
A group of objects in Java is known as collections. Java.util package contains, along with date and time facilities, internationalization, legacy collection classes, etc., the various classes and interfaces for collecting.

Alternatively, collections can be considered as a framework designed for storing the objects and manipulating the design in which the objects are stored. You can use collections to perform the following operations on objects:

1.Deletion
2.Insertion
3.Manipulation
4.Searching
5.Sorting

Following are the various constituents of the collections framework:

Classes – Array List, Linked List, Lists, and Vector
Interfaces – Collection, List, Map, Queue, Set, Sorted Map, and Sorted Set
Maps – HashMap, HashTable, LinkedHashMap, and TreeMap
Queues – Priority Queue
Sets – Hash Set, Linked Hash Set, and Tree Set

Q: Please explain Map and their types in Java.
A:
A Java Map is an object that maps keys to values. It can’t contain duplicate keys and each key can map to only one value. In order to determine whether two keys are the same or distinct, Map makes use of the equals () method. There are 4 types of Map in Java, described as follows:

HashMap - It is an unordered and unsorted map and hence, is a good choice when there is no emphasis on the order. A HashMap allows one null key and multiple null values, and doesn’t maintain any insertion order.
HashTable – Doesn’t allow anything null and has methods that are synchronized. As it allows for thread safety, the performance is slow.
LinkedHashMap – Slower than a HashMap but maintains insertion order and has a faster iteration.
TreeMap – A sorted Map providing support for constructing a sort order using a constructor.

Q: What do you mean by Priority Queue in Java?
A:
Priority queue, like a regular queue, is an abstract data type with the exception of having a priority associated with each element contained by it. The element with the high priority is served before the element with low priority in a priority queue.

Elements in a priority queue are ordered either according to the comparator or naturally. The order of the elements in a priority queue represents their relative priority.

Q: How is an Abstract class different from an Interface?
A:
There are several differences between an Abstract class and an Interface in Java, summed up as follows:

Constituents – An abstract class contains instance variables, whereas an interface can contain only constants.
Constructor and Instantiation – While an interface has neither a constructor nor it can be instantiated, an abstract class can have a default constructor that is called whenever the concrete subclass is instantiated.
Implementation of Methods – All classes that implement the interface need to provide an implementation for all the methods contained by it. A class that extends the abstract class, however, doesn’t require implementing all the methods contained in it. Only abstract methods need to be implemented in the concrete subclass.
Type of Methods – Any abstract class has both abstract as well as non-abstract methods. Interface, on the other hand, has only a single abstract method.

Q: Could you explain various types of Exceptions in Java? Also, tell us about the different ways of handling them.
A:
Java has provision for two types of exceptions:

Checked Exceptions – Classes which extend Throwable class, except Runtime exception and Error, are called checked exceptions. Such exceptions are checked by the compiler during the compile time. These type of exceptions must either have appropriate try/catch blocks or be declared using the throws keyword. ClassNotFoundException is a checked exception.
Unchecked Exceptions – Such exceptions aren’t checked by the compiler during the compile time. As such, the compiler doesn’t necessitate for handling unchecked exceptions. Arithmetic Exception and ArrayIndexOutOfBounds Exception are unchecked exceptions.
Exceptions in Java are handled in two ways:

Declaring the throws keyword – We can declare the exception using throws keyword at the end of the method. For example,
class ExceptionCheck{
public static void main(String[] args){
add();
}
public void add() throws Exception{
addition();
}
}
Using try/catch – Any code segment that is expected to yield an exception is surrounded by the try block. Upon the occurrence of the exception, it is caught by the catch block that follows the try block. For example,
class ExceptionCheck{
public static void main (String[] args) {
add();
}
public void add(){
try{
addition();
}catch(Exception e){
e.printStacktrace();
}
}
}

Q: Could you draw the Java Exception Hierarchy?
A:
Java Exception Hierarchy

Q: What role does the final keyword play in Java? What impact does it have on a variable, method, and class?
A:
The final keyword in Java is a non-access modifier that is applicable only to a class, method, or variable. It serves a different purpose based on the context where it is used.

With a class:

When a class is declared as final then it is disabled from being subclassed i.e. no class can extend the final class.

With a method:

Any method accompanying the final keyword is restricted from being overridden by the subclass.

With a variable:

A variable followed by the final keyword is not able to change the value that it holds during the program execution. So, it behaves like a constant.

Q: How do you make a thread in Java? Give examples.
A:
In order to make a thread in Java, there are two options:

Extend the Thread Class – The thread is available in the java.lang.Thread class. In order to make a thread, you need to extend a thread class and override the run method. For example,public class Addition extends Thread {
public void run() {
}
}

A disadvantage of using the thread class is that it becomes impossible to extend any other classes. Nonetheless, it is possible to overload the run () method in the class

Implement Runnable Interface – Another way of making a thread in Java is by implementing a runnable interface. For doing so, there is the need to provide the implementation for the run () method that is defined in the
interface. For example,
public class Addition implements Runnable {
public void run () {
}
}

Q: Why do we use the yield () method?
A:
The yield () method belongs to the thread class. It transfers the currently running thread to a runnable state and also allows the other threads to execute. In other words, it gives equal priority threads a chance to run. Because yield () is a static method, it does not release any lock.

Q: Can you explain the thread lifecycle in Java?
A:
The thread lifecycle has the following states and follows the following order:

New – In the very first state of the thread lifecycle, the thread instance is created and the start () method is yet to be invoked. The thread is considered alive now.
Runnable – After invoking of the start () method but before invoking the run () method, a thread is in the runnable state. A thread can also return to the runnable state from waiting or sleeping state.
Running – The thread enters the running state after the run () method is invoked. This is when the thread begins execution.
Non-Runnable – Although the thread is alive, it is not able to run. Typically, it returns to the runnable state after some time.
Terminated – The thread enters the terminated state once the run () method complete its execution. It is not alive now.

**Q: Take a look at the two code snippets below:

i.

class Adder {
Static int add(int a, int b)
{
return a+b;
}
Static double add( double a, double b)
{
return a+b;
}
public static void main(String args[])
{
System.out.println(Adder.add(11,11));
System.out.println(Adder.add(12.3,12.6));
}}
ii.

class Car {
void run(){
System.out.println(“car is running”);
}
Class Audi extends Car{
void run()
{
System.out.prinltn(“Audi is running safely with 100km”);
}
public static void main( String args[])
{
Car b=new Audi();
b.run();
}
}
What is the important difference between the two?
A:** Code snippet i. is an example of method overloading while the code snippet ii. demonstrates method overriding.

Q: What do you understand by Synchronization in Java? What is its most significant disadvantage?
A:
If several threads try to access a single block of code then there is an increased chance of producing inaccurate results. To prevent this, synchronization is used.

Using the synchronization keyword makes a thread to need a key in order to access the synchronized code. Simply, synchronization allows only one thread to access a block of code at a time.

Each Java object has a lock and every lock has only one key. A thread is able to access a synchronized method only if it can get the key to the lock of the object. Following example demonstrates synchronization:

public class ExampleThread implements Runnable {
public static void main (String[] args){
Thread t = new Thread ();
t.start ();
}
public void run(){
synchronized(object){
{
}
}
Note: It is recommended to avoid implementing synchronization for all methods. This is because when only one thread is able to access the synchronized code, the next thread needs to wait. Consequently, it results in slower performance of the program.

Q: Is it possible to write multiple catch blocks under a single try block?
A:
Yes, it is possible to write several catch blocks under a single try block. However, the approach needs to be from specific to general. Following example demonstrates the same:

public class Example {
public static void main(String args[]) {
try {
int a[]= new int[10];
a[10]= 10/0;
}
catch(ArithmeticException e)
{
System.out.println("Arithmetic exception in first catch block");
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("Array index out of bounds in second catch block");
}
catch(Exception e)
{
System.out.println("Any exception in third catch block");
}
}

Q: Can you tell the difference between execute(), executeQuery(), and executeUpdate()?
A:

execute() – Used for executing any SQL query. It returns TRUE if the result is a ResultSet, like running Select queries, and FALSE if the result is not a ResultSet, such as running an Insert or an Update query.
executeQuery() – Used for executing Select queries. It returns the ResultSet, which is not null even if there are no records matching the query. The executeQuery() method must be used when executing select queries so that it throws the java.sql.SQLException with ‘executeQuery method cannot be used for update’ message when someone tries to execute an Insert or Update statement.
executeUpdate() – Used for executing Delete/Insert/Update statement or DDL statements that returns nothing. The output varies depending on whether the statements are Data Manipulation Language (DML) statements or Data Definition Language (DDL) statements. The output is an integer and equals to the total row count for the former case, and 0 for the latter case.
Note: The execute() method needs to be used only in a scenario when there is no certainty about the type of statement. In all other cases, either use executeQuery() or executeUpdate() method.

Q: Provide an example of Hibernate architecture:
A:

Hibernate architecture

Q: Could you demonstrate how to delete a cookie in JSP with a code example?
A:
Following code demonstrates deleting a cookie in JSP:

Cookie mycook = new Cookie("name1","value1");
response.addCookie(mycook1);
Cookie killmycook = new Cookie("mycook1","value1");
killmycook . set MaxAge ( 0 );
killmycook . set Path ("/");
killmycook . addCookie ( killmycook 1 );

Q: Write suitable code examples to demonstrate the use of final, finally, and finalize.
A:

Final
The final keyword is used for restricting a class, method, and variable. A final class can’t be inherited, a final method is disabled from overriding, and a final variable becomes a constant i.e. its value can’t be changed.

class FinalVarExample {
public static void main( String args[])
{
final int a=10;
a=50; // Will result in an error as the value can’t be changed now
}
Finally
Any code inside the finally block will be executed, irrespective of whether an exception is handled or not.

class FinallyExample {
public static void main(String args[]){
try {
int x=100;
}
catch(Exception e) {
System.out.println(e);
}
finally {
System.out.println("finally block is executing");}
}
}
}
Finalize The finalize method performs the clean up just before the object is garbage collected.

class FinalizeExample {
public void finalize() {
System.out.println("Finalize is called");
}
public static void main(String args[])
{
FinalizeExample f1=new FinalizeExample();
FinalizeExample f2=new FinalizeExample();
f1= NULL;
f2=NULL;
System.gc();
}
}

Q: How does the throw keyword differ from the throws keyword?
A:
While the throws keyword allows declaring an exception, the throw keyword is used to explicitly throw an exception. Checked exceptions can’t be propagated with throw only but throws allow doing so without the need of anything else.

The throws keyword is followed by a class, whereas the throw keyword is followed by an instance. The throw keyword is used within the method but the throws keyword is used with the method signature. Furthermore, it is not possible to throw multiple exceptions, but it is possible to declare multiple exceptions.

Q: How will you distinguish processes from threads?
A:
There are several fundamental differences between a process and a thread, stated as follows:

Definition – A process is an executing instance of a program whereas, a thread is a subset of a process.
Changes – A change made to the parent process doesn’t affect child processes. However, a change in the main thread can yield changes in the behavior of other threads of the same process.
Communication – While processes require inter-process communication for communicating with sibling processes, threads are able to directly communicate with other threads belonging to the same process.
Control – Processes are controlled by the operating system and are able to control only child processes. On the contrary, threads are controlled by the programmer and are capable of exercising control over threads of the same process to which they belong.
Dependence – Processes are independent entities while threads are dependent entities
Memory – Threads run in shared memory spaces but processes run in separate memory spaces.

Q: Could you draw a comparison between Array and ArrayList?
A:
An array necessitates for giving the size during the time of declaration while an array list doesn’t necessarily require size as it changes size dynamically.

In order to put an object into an array, there is the need to specify the index. However, no such requirement is in place for an array list. While an array list is parameterized, an array is not parameterized.

Q: Please explain what do you mean by an Abstract class and an Abstract method?
A:
An abstract class in Java is a class that can’t be instantiated. Such a class is typically used for providing a base for subclasses in order to extend as well as implementing the abstract methods and overriding or using the implemented methods defined in the abstract class.

In order to create an abstract class, it needs to be followed by the abstract keyword. Any abstract class can have both abstract as well as non-abstract methods.

A method in Java that only has the declaration and not implementation is known as an abstract method. Also, an abstract method name is followed by the abstract keyword. Any concrete subclass that extends the abstract class must provide an implementation for abstract methods.

Q: What do you know about Interface in Java?
A:
A Java interface is a template that has only method declarations and not method implementations. It is a workaround for achieving multiple inheritances in Java.

Some worth remembering important points regarding Java interfaces are:

A class that implements the interface must provide an implementation for all methods declared in the interface
All methods in an interface are internally public abstract void
All variables in an interface are internally public static final
Classes do not extend but implement interfaces

Q: What is the join () method? Give an example.
A:
We use the join () method for joining one thread with the end of the currently running thread. It is a non-static method and has an overloaded version. Consider the example below:

public static void main (String[] args) {
Thread t = new Thread ();
t.start();
t.join();
}

The main thread starts execution in the aforementioned example. As soon as the execution reaches the code t.start() then the thread t starts its own stack for execution. The JVM switches between the main thread and the thread t here.

Once the execution reaches the t.join() then the thread t alone is executed and allowed to complete its task. Afterward, the main thread resumes execution.

Q: How do you make a thread stop in Java?
A:
There are three methods in Java to stop the execution of a thread:

Blocking – This method is used to put the thread in a blocked state. The execution resumes as soon as the condition of the blocking is met. For instance, the ServerSocket.accept() is a blocking method that listens for incoming socket connection and resumes the blocked thread only when a connection is made.
Sleeping – This method is used for delaying the execution of the thread for some time. A thread upon which the sleep() method is used is said to enter the sleep state. It enters the runnable state as soon as it wakes up i.e. the sleep state is finished. The time for which the thread needs to enter the sleep state is mentioned inside the braces of the sleep() method. It is a static method.
Waiting – Although it can be called on any Java object, the wait() method can only be called from a synchronized block.

Q: What purpose do the Volatile variable serve in Java?
A:
The value stored in a volatile variable is not read from the thread’s cache memory but from the main memory. Volatile variables are primarily used during synchronization.

Q: Please compare Serialization with Deserialization in Java.
A:
Serialization is the process by which Java objects are converted into the byte stream. Deserialization is the exact opposite process of serialization where Java objects are retrieved from the byte stream.

A Java object is serialized by writing it to an ObjectOutputStream and deserialized by reading it from an ObjectInputStream.

That completes the list of 28 essential Java interview questions. What do you think about the list we compiled? Let us know by dropping your comments in the dedicated window below. Also, check out these best Java tutorials to further refine your Java skill set.

Originally Posted: https://hackr.io/blog/java-interview-questions

Top comments (9)

Collapse
 
ld00d profile image
Brian Lampe

A class that implements the interface must provide an implementation for all methods declared in the interface

There's a new-ish (java 8) thing called a "default method" that has a default implementation that doesn't require implementation from the class.

Collapse
 
stargator profile image
Stargator

The following question was not answered:

Provide an example of Hibernate architecture:

Collapse
 
vijaykhatri96 profile image
Vijay Singh Khatri

Sorry, I missed that just uploaded it.

Collapse
 
stargator profile image
Stargator

FYI, I just noticed some Qs and As that had ** appended without a "opening" ** to start a bolded font.

Thread Thread
 
vijaykhatri96 profile image
Vijay Singh Khatri

Ok, I will fix them as well.

Collapse
 
stargator profile image
Stargator

No problem, just noticed it.

Collapse
 
mohithsharma profile image
Mohithsharma

Hey,

Thanks for the post. It's really useful and informative. I've also found a resource for getting yourself prepared for Java 8 questions. This might help :)

Collapse
 
techatom1 profile image
Tech Atom

Thanks for sharing, this helps all the java aspirants, I also found this techgeekbuzz.com/core-java-intervi..., hope might help in the interview as well.

Collapse
 
tomerl101 profile image
Tomer

great post!