Java is one of the most popular programming language in today's world and thus learning it to a great extent can be a huge asset for anyone. Therefore I have brought an extensive list of some of the most tricky Java interview questions that will surely set you apart whether you are preparing for your technical interview or are a Java enthusiast.
So let's get started with our exquisite list of the most tricky Java interview question.
1. What is Garbage collection in java?
In languages like C and C++ where programmer is responsible for both
creation and destruction of objects, usually the programmer neglects the destruction
of objects . Due to this negligence, at certain point the memory may get
exhausted and sufficient memory may not be available for creation of new
objects causing entire program to terminate abnormally.
But in Java, the
programmer need not to care for destroying objects explicitly. Garbage
Collector is used to free heap memory by destroying unreachable objects automatically by itself without the programmer needing to worry about it.
Unreachable
objects : An object is said to be unreachable if and only if it doesn’t
contain any reference to it in the program (direct or indirect).
Note
: An object is only eligible for garbage collection, if and only if it is
unreachable.
Example :
CodingWithArt obj = new CodingWithArt(); // object is reachable via the reference in 'obj' obj = null; // the CodingWithArt object is unreachable now.
In the above example there is no reference to obj and therefore it is eligible for garbage collection. It is recommended to make an object unreachable if it is not required so that it's memory can be utilized somewhere else.
Requesting JVM to run Garbage Collector
Garbage collector can not be invoked by programmer directly. If you have made an object eligible for garbage collection, you don't know when the garbage collector will be invoked. You have to wait for JVM to run the memory cleanup program that performs garbage collection. But we can request the JVM to invoke the garbage collector using System.gc() method. The System class contain static method gc() for requesting JVM to run Garbage Collector.
2. Explain mark and sweep algorithm for garbage collection.
To determine which objects are no longer in use, the JVM intermittently runs what is called as mark-and-sweep algorithm.
Mark and Sweep Algorithm operates in two phases: Mark phase and Sweep phase
1.) Mark Phase
When an object is created, its mark bit is set to 0 (false). Now in the Mark phase, we set the marked bit for all the reachable objects (which have a direct or indirect reference) to 1 (true). This can be performed by using a graph traversal algorithm such as depth first search and breadth first search. Any object in the program is a node and an edge represents an object referring another object.
DFS Algorithm - Mark phase:
MarkPhase(root) { If marked(root) == false then marked(root) = true For each obj referenced by root MarkPhase(obj) }
In the above program, root is a directly accessible variable that refer to an object.
2. Sweep Phase
In this phase all the unreachable objects are actually cleared from the heap memory. All the objects on the heap memory are accessed one by one :
a. if mark bit is false, means it is unreachable so its memory is cleared from heap.
b. if mark bit is true, means it is reachable and thus we just unset its marked bit (0) for future use.
SweepPhase() { For each object obj in heap If marked(obj) == true then marked(obj) = false else heap.release(obj) }
a) All the objects have their marked bits set to false.
b) Reachable objects are marked true
c) Non reachable objects are cleared from the heap.
3. What is the difference between checked exception and unchecked exception.
There are two types of exceptions in Java: checked exception and
unchecked exception.
1. Checked Exception :
In simple terms, checked exceptions are checked at compile-time.Therefore if a
method is capable of causing an exception, then it must either handle it using
try-catch block otherwise it must specify it using 'throws' keyword so
that the caller of the method can guard itself from the exception.
Examples : ClassNotFoundException, SQLException, IOException
class CodingWithArt {
void func() throws IOException {
FileReader file = new FileReader("C:\\folder\\test.txt");
BufferedReader fileInput = new BufferedReader(file);
System.out.println(fileInput.readLine());
fileInput.close();
}
}
Since IOExceptionn is a checked exception therefore we have to use throws keyword with the func() function otherwise we will get a compile time error.
2. Unchecked exception :
Unchecked exceptions are not checked at compile time. It means if your program is throwing an unchecked exception and even if you didn’t handle that exception, the program won’t give a compilation error. It is the programmer's duty to judge the conditions in advance, that can cause such exceptions and handle them appropriately otherwise this may result in errors.
Examples : NullPointerException, ArrayIndexOutOfBoundsException,
ArithmeticException
In Java, all exceptions under Error and
RuntimeException classes are unchecked exceptions, everything else under
throwable is checked.
4. Differentiate between JDK , JRE and JVM .
JDK (Java Development Kit):
The Java Development Kit (JDK) is a software development environment used for
developing Java applications and applets. It includes the Java Runtime
Environment (JRE), a compiler (javac), an archiver (jar), and other
development tools needed in Java. JDK helps Java developers to code and run
Java programs. It can be installed on Windows, Unix, and Mac operating
systems.
JRE (Java Runtime Envirroment):
The Java Runtime Environment (JRE) provides the minimum requirements for
executing a Java application; it consists of the Java Virtual Machine (JVM),
class libraries, and supporting files.
It uses important package classes
like math, swingetc, util, lang, awt, and runtime libraries.
JVM (Java Virtual Machine) :
Java Virtual Machine (JVM) is an engine that provides a runtime environment to
drive the Java Code or applications. Whatever Java program you run using JRE
or JDK goes into JVM and JVM is responsible for executing the java program
line by line hence it is also known as interpreter.
![]() |
|
JDK vs JRE vs JVM |
5. What is the difference between StringBuffer and StringBuilder in Java.
String class is immutable (cannot be modified) in Java, therefore
whenever String manipulations are performed, automatically a new String would
be generated by discarding the older one. To avoid garbage in heap, Java came
up with StringBuffer and StringBuilder.
sSringBuffer and
StringBuffer both are mutable classes in java, i.e they allow the stored
string to be modified.
Differences between StringBuffer and StringBuilder :
6. What is multithreading ? How can we create thread in java?
A thread is a lightweight sub-process, the smallest unit of processing.
Multithreading is a Java feature that allows concurrent execution of two or
more parts of a program for maximum utilization of CPU. We can create multiple
threads in a program which can simultaneously perofrm their operations.
Threads
can be created by using two mechanisms :
1. Extending the Thread class
2.
Implementing the Runnable Interface
1. Extending the Thread class
We create a class that extends the java.lang.Thread class. We
have to override the run() method available in the Thread class. A thread
begins its life inside run() method. We create an object of our new class and
call start() method to start the execution of a thread. start() invokes the
run() method on the Thread object.
// Java code for thread creation by extending the Thread class class CodingWithArt extends Thread { public void run() { try { // Displaying the running thread System.out.println ("Thread " + Thread.currentThread().getId() + " is running"); } catch (Exception e) { // Throwing an exception System.out.println ("Exception caught"); } } } // Main Class public class Multithread { public static void main(String[] args) { int n = 2; // Number of threads for (int i=0; i!=n; i++) { CodingWithArt object = new CodingWithArt(); object.start(); } } }
2. Implementing the Runnable Interface
Create a new class which implements java.lang.Runnable interface and overrides run() method. Then we instantiate a Thread object and call start() method on this object.
// Java code for thread creation by implementing // the Runnable Interface class CodingWithArt implements Runnable { public void run() { try { // Displaying the running thread System.out.println ("Thread " + Thread.currentThread().getId() + " is running"); } catch (Exception e) { // Throwing an exception System.out.println ("Exception caught"); } } } // Main Class class Multithread { public static void main(String[] args) { int n = 2; // Number of threads for (int i=0; i!=n; i++) { Thread object = new Thread(new CodingWithArt()); object.start(); } } }
Thread Class vs Runnable Interface
Generally both Thread and Runnable are equally effective in creating threads. But since Java does not support multiple inheritance, the class which inherits Thread class cannot inherit any other class. This can be a disadvantage in some situations. This problem does not arise when implementing the Runnable interface, because a class can implement multiple interfaces together and can also extend a class and interface together.