Open In App

Advanced Topics Interview Questions - Java Programming

Last Updated : 08 Aug, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

As you progress in Java, understanding advanced features becomes essential for writing efficient, clean, and maintainable code. These are commonly tested in technical interviews for backend, data, and system programming roles.

This covers key advanced Java interview topics with questions and in-depth answers

1. What is Exception Handling & How many types of exceptions can occur in a Java program?

An Exception is an Event that interrupts the normal flow of the program and requires special processing. During the execution of a program, errors and unplanned occurrences can be dealt with by using the Java Exception Handling mechanism. Below are some reasons why Exceptions occur in Java:

  • Device failure
  • Loss of Network Connection
  • Code Errors
  • Opening an Unavailable file
  • Invalid User Input
  • Physical Limitations (out of disk memory)
Types-of-Exception-in-Java-660

There are generally two types of exceptions in Java:

  • Built-in Exceptions: Built-in exceptions in Java are provided by the Java Libraries. These exceptions can be further divided into two subcategories i.e., checked and unchecked Exceptions. Below are some of the built-in exceptions in Java:
  1. ArrayIndexOutOfBoundsExceptions
  2. ClassNotFoundException
  3. FileNotFoundException
  4. IOException
  5. NullPointerException
  6. ArithmeticException
  7. InterruptedException
  8. RuntimeException
  • User-Defined Exceptions: User-defined exceptions are defined by the programmers themselves to handle some specific situations or errors which are not covered by built-in exceptions. To define user-defined exceptions a new class that extends the appropriate exception class must be defined. User-defined Exceptions in Java are used when the built-in exceptions are in Java.

2. Difference between an Error and an Exception.

Errors

Exceptions

Recovering from Errors is not possible.                            

Recover from exceptions by either using a try-catch block or throwing exceptions back to the caller.

Errors are all unchecked types in Java.

It includes both checked as well as unchecked types that occur.

Errors are mostly caused by the environment in which the program is running.

The program is mostly responsible for causing exceptions.

Errors can occur at compile time as well as run time. Compile Time: Syntax Error, Run Time: Logical Error.

All exceptions occur at runtime but checked exceptions are known to the compiler while unchecked are not.

They are defined in java.lang.Error package.

They are defined in java.lang.Exception package

Examples: java.lang.StackOverflowError, java.lang.OutOfMemoryError

Examples: Checked Exceptions: SQLException, IOException Unchecked Exceptions: ArrayIndexOutOfBoundException, NullPointerException, ArithmeticException.

3. Explain the hierarchy of Java Exception classes.

Exception-Handling-768


All exception and error types in Java are subclasses of the class throwable, which is the base class of the hierarchy. This class is then used for exceptional conditions that user programs should catch. NullPointerException is an example of such an exception. Another branch, error is used by the Java run-time system to indicate errors having to do with the JRE. StackOverflowError is an example of one of such error.

4. Explain Runtime Exceptions.

Runtime Exceptions are exceptions that occur during the execution of a code, as opposed to compile-time exceptions that occur during compilation. Runtime exceptions are unchecked exceptions, as they aren't accounted for by the JVM.

Examples of runtime exceptions in Java include:

  • NullPointerException: This occurs when an application attempts to use a null object reference.
  • ArrayIndexOutOfBoundsException: This occurs when an application attempts to access an array index that is out of bounds.
  • ArithmeticException: This occurs when an application attempts to divide by zero.
  • IllegalArgumentException: This occurs when a method is passed on an illegal or inappropriate argument.

Unlike checked exceptions, runtime exceptions do not require a declaration in the throws clause or capture in a try-catch block. However, handling runtime exceptions is advisable in order to provide meaningful error messages and prevent a system crash. Because runtime exceptions provide more specific information about the problem than checked exceptions, they enable developers to detect and correct programming errors more easily and quickly.

5. What is NullPointerException?

It is a type of run-time exception that is thrown when the program attempts to use an object reference that has a null value. The main use of NullPointerException is to indicate that no value is assigned to a reference variable, also it is used for implementing data structures like linked lists and trees. 

6. When is the ArrayStoreException thrown?

ArrayStoreException is thrown when an attempt is made to store the wrong type of object in an array of objects.

Example:

Java
// Java Program to implement
// ArrayStoreException
public class GFG {
    public static void main(String args[])
    {
        // Since Double class extends Number class
        // only Double type numbers
        // can be stored in this array
        Number[] a = new Double[2];
        // Trying to store an integer value
        // in this Double type array
        a[0] = new Integer(4);
    }
}

Example:

Exception in thread "main" java.lang.ArrayStoreException: java.lang.Integer
at GFG.main(GFG.java:6)

7. What is the difference between Checked Exception and Unchecked Exception?

Checked Exception:

Checked Exceptions are the exceptions that are checked during compile time of a program. In a program, if some code within a method throws a checked exception, then the method must either handle the exception or must specify the exception using the throws keyword. 

Checked exceptions are of two types: 

  • Fully checked exceptions: all its child classes are also checked, like IOException, and InterruptedException.
  • Partially checked exceptions: some of its child classes are unchecked, like an Exception. 

Unchecked Exception:

Unchecked are the exceptions that are not checked at compile time of a program. Exceptions under Error and RuntimeException classes are unchecked exceptions, everything else under throwable is checked. 

8. What is the base class for Error and Exception?

Exception-Handling-768

Error is an illegal operation performed by the user which causes abnormality in the program. Exceptions are the unexpected events or conditions that comes while running the program, exception disrupts the normal flow of the program’s instructions.

Errors and Exceptions both have a common parent class which is java.lang.Throwable class.

9. Is it necessary that each try block must be followed by a catch block?

No, It is not necessary to use catch block after try block in Java as we can create another combination with finally block. Finally is the block which runs despite the fact that the exception is thrown or not.

10. What is exception propagation?

Exception propagation is a process in which the exception is dropped from to the top to the bottom of the stack. If not caught once, the exception again drops down to the previous method, and so on until it gets caught or until it reaches the very bottom of the call stack.

11. What will happen if you put System.exit(0) on the try or catch block? Will finally block execute?

System.exit(int) has the capability to throw SecurityException. So, if in case of security, the exception is thrown then finally block will be executed otherwise JVM will be closed while calling System. exit(0) because of which finally block will not be executed.

12. What do you understand by Object Cloning and how do you achieve it in Java?

It is the process of creating an exact copy of any object. In order to support this, a java class has to implement the Cloneable interface of java.lang package and override the clone() method provided by the Object class the syntax of which is:

Protected Object clone() throws CloneNotSupportedException{ return (Object)super.clone();}In case the Cloneable interface is not implemented and just the method is overridden, it results in CloneNotSupportedException in Java.

13. How do exceptions affect the program if it doesn't handle them?

Exceptions are responsible for abruptly terminating the running of the program while executing and the code written after the exception occurs is not executed.

14. What is the use of the final keyword?

The final keyword is used to make functions non-virtual. By default, all the functions are virtual so to make it non-virtual we use the final keyword.

15. What purpose do the keywords final, finally, and finalize fulfill?

  • final: final is a keyword is used with the variable, method, or class so that they can't be overridden. 

Example:

Java
// Java Program to use final
// keyword
import java.io.*;
// Driver Class
class GFG {
    // Main function
    public static void main(String[] args)
    {
        final int x = 100;
        x = 50;
    }
}

Output:

./GFG.java:6: error: cannot assign a value to final variable x
x=50;
^
1 error

  • finally: finally is a block of code used with "try-catch" in exception handling. Code written in finally block runs despite the fact exception is thrown or not.

Example:

Java
// Java Program to implement finally
import java.io.*;
// Driver class
class GFG {
    // Main function
    public static void main(String[] args)
    {
        int x = 10;
        // try block
        try {
            System.out.println("Try block");
        }
        // finally block
        finally {
            System.out.println(
                "Always runs even without exceptions");
        }
    }
}

Output
Try block
Always runs even without exceptions
  • finalize: It is a method that is called just before deleting/destructing the objects which are eligible for Garbage collection to perform clean-up activity.

Example:

Java
/*package whatever // do not write package name here */
import java.io.*;
class GFG {
    public static void main(String[] args)
    {
        System.out.println("Main function running");
        System.gc();
    }
    // Here overriding finalize method
    public void finalize()
    {
        System.out.println("finalize method overridden");
    }
}

Output
Main function running

16. What is the difference between this() and super() in Java?

this( )

super( )

It represents the current instance of the class.

It represents the current instance of the parent class.

Calls the default constructor of the same class.

Calls the default constructor of the base class.

Access the methods of the same class.

Access the methods of the parent class.

Points current class instance.

Points the superclass instance.

17. What is multitasking?

Multitasking in Java refers to a program's capacity to carry out several tasks at once. Threads, which are quick operations contained within a single program, can do this. Executing numerous things at once is known as multitasking.

Example:

Java
// Java program for multitasking
import java.io.*;
 class MyThread extends Thread {
    public void run()
    {
        // Code to be executed in this thread
        for (int i = 0; i < 10; i++) {
            System.out.println(
                "Thread " + Thread.currentThread().getId()
                + ": " + i);
        }
    }
}
public class GFG {
    public static void main(String[] args)
    {
        MyThread thread1 = new MyThread();
        MyThread thread2 = new MyThread();
        // Start the threads
        thread1.start();
        thread2.start();
    }
}

18. What do you mean by a Multithreaded program?

Multithreaded programs in Java contain threads that run concurrently instead of running sequentially. A computer can use its resources more efficiently by combining multiple tasks at once. Any program with multithreading allows more than one user to simultaneously use the program without running multiple copies. A multithreaded program is designed to run multiple processes at the same time which can improve the performance of a program and allows the program to utilize multiple processors and improves the overall throughput.

19. What are the advantages of multithreading?

There are multiple advantages of using multithreading which are as follows:

  • Responsiveness: User Responsiveness increases because multithreading interactive application allows running code even when the section is blocked or executes a lengthy process.
  • Resource Sharing: The process can perform message passing and shared memory because of multithreading.
  • Economy: We are able to share memory because of which the processes are economical.
  • Scalability: Multithreading on multiple CPU machines increases parallelism.
  • Better Communication: Thread synchronization functions improves inter-process communication.
  • Utilization of multiprocessor architecture
  • Minimized system resource use

20. What are the two ways in which Thread can be created?

Multithreading is a Java feature that allows concurrent execution of two or more parts of a program for maximum utilization of the CPU. In general, threads are small, lightweight processes with separate paths of execution. These threads use shared memory, but they act independently, thus if any one thread fails it does not affect the other threads. There are two ways to create a thread:

  • By extending the Thread class
  • By implementing a Runnable interface.

By extending the Thread class

We create a class that extends the java.lang.Thread class. This class overrides the run() method available in the Thread class. A thread begins its life inside run() method. 

Syntax:

public class MyThread extends Thread {
public void run() {
// thread code goes here
}
}

By implementing the Runnable interface

We create a new class that implements java.lang.Runnable interface and override run() method. Then we instantiate a Thread object and call the start() method on this object. 

Syntax:

public class MyRunnable implements Runnable {
public void run() {
// thread code goes here
}
}

21. What is a thread?

Threads in Java are subprocess with lightweight with the smallest unit of processes and also has separate paths of execution. These threads use shared memory but they act independently hence if there is an exception in threads that do not affect the working of other threads despite them sharing the same memory. A thread has its own program counter, execution stack, and local variables, but it shares the same memory space with other threads in the same process. Java provides built-in support for multithreading through the Runnable interface and the Thread class.

22. Differentiate between process and thread?

A process and a thread are both units of execution in a computer system, but they are different in several ways:

Process

Thread

A process is a program in execution.

A thread is a single sequence of instructions within a process.

The process takes more time to terminate.

The thread takes less time to terminate.

The process takes more time for context switching.

The thread takes less time for context switching.

The process is less efficient in terms of communication.

Thread is more efficient in terms of communication.

The process is isolated.

Threads share memory.

The process has its own Process Control Block, Stack, and Address Space.                   

Thread has Parents’ PCB, its own Thread Control Block, and Stack and common Address space.

The process does not share data with each other.

Threads share data with each other.

23. Describe the life cycle of the thread?

Cycle-of-thread-768

A thread in Java at any point in time exists in any one of the following states. A thread lies only in one of the shown states at any instant: 

  1. New: The thread has been created but has not yet started.
  2. Runnable: The thread is running, executing its task, or is ready to run if there are no other higher-priority threads.
  3. Blocked: The thread is temporarily suspended, waiting for a resource or an event.
  4. Waiting: The thread is waiting for another thread to perform a task or for a specified amount of time to elapse.
  5. Terminated: The thread has completed its task or been terminated by another thread.

24. Explain suspend() method under the Thread class.

The suspend() method of the Thread class in Java temporarily suspends the execution of a thread. When a thread is suspended it goes into a blocked state and it would not be scheduled by the operating system which means that it will not be able to execute its task until it is resumed. There are more safer and flexible alternatives to the suspend() methods in the modern java programming language. This method does not return any value.

Syntax:

public final void suspend();

Example:

Java
// Java program to show thread suspend() method
import java.io.*;
class MyThread extends Thread {
    public void run()
    {
        for (int i = 0; i < 10; i++) {
            System.out.println(" Running thread : " + i);
            try {
                Thread.sleep(1000);
            }
            catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}
class GFG {
    public static void main(String[] args)
    {
        MyThread t1 = new MyThread();
        t1.start();
        try {
            Thread.sleep(3000);
        }
        catch (InterruptedException e) {
            e.printStackTrace();
        }
        // suspend the execution of the thread
        t1.suspend();
        System.out.println("Suspended thread ");
        try {
            Thread.sleep(3000);
        }
        catch (InterruptedException e) {
            e.printStackTrace();
        }
        // resume the execution of the thread
        t1.resume();
        System.out.println("Resumed thread");
    }
}

25. Explain the main thread under Thread class execution.

Java provides built-in support for multithreaded programming. The main thread is considered the parent thread of all the other threads that are created during the program execution. The main thread is automatically created when the program starts running. This thread executes the main method of the program. It is responsible for executing the main logic of the Java program as well as handling the user input operations. The main thread serves as the base thread from which all other child threads are spawned. 

Thread-Class-Execution-768

26. What is a daemon thread?

A daemon thread in Java is a low-priority thread that is used to perform background operations or tasks which are used to perform continuously. such as Garbage collection, Signal dispatches, Action listeners, etc. Daemon threads in Java have lower priority than user threads, which means they can only execute when no user threads are running. Daemon threads in Java are useful features that are required for background tasks that do not require explicit shutdown or finalization. It allows more efficient use of system resource and are used to simplify resources and can simplify long-running tasks.

27. What are the ways in which a thread can enter the waiting state?

Thread is a lightweight process that runs concurrently with the other thread inside a single process. Each thread can execute a different task and share the resources within a single process. Thread in Java can enter the waiting state in many different ways:

  • Sleep() method Call: The sleep () method is used to pause the execution of the thread for a specific amount of time. While the thread is paused it goes into the waiting state.
  • Wait() method: This method is used to wait a thread until the other thread signals it to wake up. Thread goes into the waiting state until it receives a notification from another thread.
  • Join() method: Join() method can be used to wait for thread to finish the execution. Calling thread goes into the waiting state until the target thread is completed.
  • Waiting for I/O operations: If the thread is waiting for Input/Output operation to complete, it goes into the waiting state until the operation is finished.
  • Synchronization Issues: If there are any synchronization issues in a multi-threaded application, threads may go into the waiting state until the synchronization issues are resolved.

28. How does multi-threading take place on a computer with a single CPU?

Java uses a technique called time-sharing, commonly referred to as time-slicing, to implement multi-threading on computers with a single CPU. The appearance of parallel execution is created by the CPU switching between active threads. The operating system is in charge of allocating CPU time to each thread sequentially and scheduling the threads.

In order to stop threads from interacting with one another and creating race situations or other issues, Java has a number of ways to govern the behavior of threads, including synchronization and locking. It is feasible to create multi-threaded programmers that operate correctly and effectively on a machine with a single CPU by regulating the interaction between threads and making sure that crucial code parts are synchronized. In contrast to running the same program on a computer with multiple CPUs or cores, multi-threading on a single CPU can only give the appearance of parallelism, and actual performance gains may be modest. The operating system divides the CPU time that is available when numerous threads are running on a single CPU into small time slices and gives each thread a time slice to execute. Rapid switching between the threads by the operating system creates the appearance of parallel execution. The switching between threads appears to be immediate because the time slices are often very tiny, on the order of milliseconds or microseconds.

29. What are the different types of Thread Priorities in Java? And what is the default priority of a thread assigned by JVM?

Priorities in threads is a concept where every thread is having a priority which in layman’s language one can say every object is having priority here which is represented by numbers ranging from 1 to 10. There are different types of thread properties in Java mentioned below:

  • MIN_PRIORITY
  • MAX_PRIORITY
  • NORM_PRIORITY 

By default, the thread is assigned NORM_PRIORITY.

30. Why Garbage Collection is necessary in Java?

For Java, Garbage collection is necessary to avoid memory leaks which can cause the program to crash and become unstable. There is no way to avoid garbage collection in Java. Unlike C++, Garbage collection in Java helps programmers to focus on the development of the application instead of managing memory resources and worrying about memory leakage. Java Virtual Machine (JVM) automatically manages the memory periodically by running a garbage collector which frees up the unused memory in the application. Garbage collection makes Java memory efficient because it removes unreferenced objects from the heap memory.

31. What is the drawback of Garbage Collection?

Apart from many advantages, Garbage Collector has certain drawbacks mentioned below:

  1. The main drawback to Garbage collection is that it can cause pauses in an application's execution as it works to clear the memory which slows down the performance of the application. 
  2. The Process of Garbage collection is non-deterministic which makes it difficult to predict when garbage collection occurs which causes unpredictable behavior in applications. For Example, if we write any program then it is hard for programmers to decide if the issue is caused by garbage collection or by any other factors in the program. 
  3. Garbage collection can also increase memory usage if the program creates and discards a lot of short-lived objects.

32. Explain the difference between a minor, major, and full garbage collection.

The Java Virtual Machine (JVM) removes objects that are no longer in use using a garbage collector which periodically checks and removes these objects. There are different types of garbage collection in the JVM, each with different characteristics and performance implications. The main types of garbage collection are:

  • Minor garbage collection: Also known as young generation garbage collection, this type of garbage collection is used to collect and reclaim memory that is used by short-lived objects (objects that are quickly created and discarded). 
  • Major garbage collection: Also known as old-generation garbage collection, this type of garbage collection is used to collect and reclaim memory that is used by long-lived objects (objects that survive multiple minor garbage collections and are promoted to the old generation).
  • Full garbage collection: During full garbage collection, memories from all generations are collected and reclaimed, including memories of young and old. A full garbage collection normally takes longer to complete than a minor or major garbage collection which causes that app to pause temporarily.

33. How will you identify major and minor garbage collections in Java?

Major garbage collection works on the survivor space and Minor garbage collection works on the Eden space to perform a mark-and-sweep routine. And we can identify both of them based on the output where the minor collection prints "GC", whereas the major collection prints "Full GC" for the case where the garbage collection logging is enabled with "-XX:PrintGCDetails" or "verbose:gc".

34. What is a memory leak, and how does it affect garbage collection?

In Java Memory leaks can be caused by a variety of factors, such as not closing resources properly, holding onto object references longer than necessary, or creating too many objects unnecessarily. There are situations in which garbage collector does not collect objects because there is a reference to those objects. In these situations where the application creates lots of objects and does not use them and every object has some valid references, a Garbage collector in Java cannot destroy the objects. These useless objects which do not provide any value to the program are known as Memory leaks. Memory leaks can impact garbage collection negatively by preventing the garbage collector from reclaiming unused memory. This behavior will lead to slow performance or sometimes system failure. In a program, it is important to avoid memory leaks by managing resources and object references properly. 

Example:

Java
// Java Program to demonstrate memory leaks
import java.io.*;
import java.util.Vector;
class GFG {
    public static void main(String[] args)
    {
        Vector a = new Vector(21312312);
        Vector b = new Vector(2147412344);
        Vector c = new Vector(219944);
        System.out.println("Memory Leak in Java");
    }
}

Output:

Exception in thread "main" java.lang.OutOfMemoryError: Java heap space
at java.base/java.util.Vector.<init>(Vector.java:142)
at java.base/java.util.Vector.<init>(Vector.java:155)
at GFG.main(GFG.java:9)

35. Name some classes present in java.util.regex package.

Regular Expressions or Regex in Java is an API used for searching and manipulating of strings in Java. It creates String patterns that can extract the data needed from the strings or can generalize a pattern. There are 3 Classes present in java.util.regex mentioned below:

  • Pattern Class: Can define patterns
  • Matcher Class: Can perform match operations on text using patterns
  • PatternSyntaxException Class: Can indicate a syntax error in a regular expression pattern.

Also, apart from the 3 classes package consists of a single interface MatchResult Interface which can be used for representing the result of a match operation.

36. Write a regular expression to validate a password. A password must start with an alphabet and followed by alphanumeric characters; Its length must be in between 8 to 20.

regex = “^(?=.*[0-9])(?=.*[a-z])(?=.*[A-Z])(?=.*[@#$%^&-+=()])(?=\\S+$).{8, 20}$”

Explanation:

  • ^ used for starting character of the string.
  • (?=.*[0-9]) used for a digit must occur at least once.
  • (?=.*[a-z]) used for a lowercase alphabet must occur at least once.
  • (?=.*[A-Z]) used for an upper case alphabet that must occur at least once in the substring.
  • (?=.*[@#$%^&-+=()] used for a special character that must occur at least once.
  • (?=\\S+$) white spaces don’t allow in the entire string.
  • .{8, 20} used for at least 8 characters and at most 20 characters.
  • $ used for the end of the string.

37. What is JDBC?

JDBC standard API is used to link Java applications and relational databases. It provides a collection of classes and interfaces that let programmers to use the Java programming language to communicate with the database. The classes and interface of JDBC allow the application to send requests which are made by users to the specified database. There are generally four components of JDBC by which it interacts with the database:

  • JDBC API
  • JDBC Driver manager
  • JDBC Test Suite
  • JDBC-ODBC Bridge Drivers
JDBC-768

38. What is JDBC Driver?

JDBC Driver is a software component that is used to enable a Java application to interact with the database. JDBC provides the implementation of the JDBC API for a specific database management system, which allows it to connect the database, execute SQL statements and retrieve data. There are four types of JDBC drivers:

  • JDBC-ODBC Bridge driver
  • Native-API driver
  • Network Protocol driver
  • Thin driver
JDBC-Driver-660

39. What are the steps to connect to the database in Java?

There are certain steps to connect the database and Java Program as mentioned below:

  • Import the Packages
  • Load the drivers using the forName() method 
  • Register the drivers using DriverManager 
  • Establish a connection using the Connection class object
  • Create a statement
  • Execute the query
  • Close the connections

40. What are the JDBC API components?

JDBC API components provide various methods and interfaces for easy communication with the databases also it provides packages like java Se and java EE which provides the capability of write once run anywhere (WORA).

Syntax:

java.sql.*;

41. What is JDBC Connection interface?

Java database connectivity interface (JDBC) is a software component that allows Java applications to interact with databases. To enhance the connection, JDBC requires drivers for each database.

42. What does the JDBC ResultSet interface?

JDBC ResultSet interface is used to store the data from the database and use it in our Java Program. We can also use ResultSet to update the data using updateXXX() methods. ResultSet object points the cursor before the first row of the result data. Using the next() method, we can iterate through the ResultSet.

43. What is the JDBC Rowset?

A JDBC RowSet provides a way to store the data in tabular form. RowSet is an interface in java that can be used within the java.sql package. The connection between the RowSet object and the data source is maintained throughout its life cycle. RowSets are classified into five categories based on implementation mentioned below:

  1. JdbcRowSet
  2. CachedRowSet
  3. WebRowSet
  4. FilteredRowSet
  5. JoinRowSet

44. What is the role of the JDBC DriverManager class?

JDBC DriverManager class acts as an interface for users and Drivers. It is used in many ways as mentioned below: 

  • It is used to create a connection between a Java application and the database. 
  • Helps to keep track of the drivers that are available.
  • It can help to establish a connection between a database and the appropriate drivers.
  • It contains all the methods that can register and deregister the database driver classes.
  • DriverManager.registerDriver() method can maintain the list of Driver classes that have registered themselves.

Article Tags :
Practice Tags :

Similar Reads