40 Most Asked Core Java Interview Questions You Must Prepare in 2024

Related Courses

Java happens to be one of the most powerful yet flexible programming languages, known for its involvement in data processing, application development and large-scale systems generally. It gives developers solid frameworks and tools that enable them to do complex computations and create sophisticated management models that are useful in data management and analysis.

Why Choose Java?

  • Industry Leader: For a long time, Java has been a dependable software development language that many organizations utilize to create applications that can scale up or down as required (Berger, 2019). Its durability as well as versatility makes it the preferred option for enterprise level development.
  • Vast Open Source Ecosystem: There exists an extensive range of open source libraries associated with Java which makes it flexible enough to meet different project requirements with ease when selecting the most appropriate tools.
  • Competitive Advantage: Today’s developers and engineers want faster information processing, extraction of valuable insights, and huge datasets modeling in this rapidly changing tech world (Mohammed et al., 2017). The performance and scalability that Java has, becomes another reason why it can be used to tackle these issues challenging developers today.
  • Broad Versatility: Java provides support for several libraries and frameworks rendering it ideal for different functions ranging from data handling to full-fledged application development. By familiarizing yourself with these libraries, you will speed up your development work and make it more reliable.
  1. Can class have private and protected as access modifier?

No, class does not have private and protected as access modifier, class can be default and public.
Example:

private class NIT{ //error
}
protected class NIT1 // error
{   
}
  1.  What is the difference between Abstraction and Encapsulation?

Abstraction is the method of hiding the unwanted information. Whereas encapsulation is a method to hide the data in a single entity or unit along with a method to protect information from outside.
In abstraction, implementation complexities are hidden using abstract classes and interfaces. While in encapsulation, the data is hidden using methods of getters and setters.

  1. Why final and abstract cannot be used at a time?

If we declare class as abstract it must be extended by another class but if we declare final class it cannot be extended by other class.
Example:

final class NIT{
   
}
class NIT1 extends NIT // error because final class cannot be extended
{   
}
  1. What is Object Cloning?

Object cloning means exact copy of Object by using Cloneable interface must be implemented by class and if you not implemented it throws cloneNotSupportedException
Example:

public class InterviewTest implements Cloneable {
    int id;
    String name;
    public InterviewTest(int id, String name) {
        this.id=id;
        this.name = name;
    }
   
    @Override
    protected Object clone() throws CloneNotSupportedException {
        return super.clone();
    }
       
    public static void main(String[] args) {
        InterviewTest nit = new InterviewTest(1,"NIT");
        System.out.println(nit.id+" "+nit.name);
        try {
            InterviewTest nit1 = (InterviewTest)nit.clone(); // Object cloning
            System.out.println(nit1.id+" "+nit1.name);
        } catch (CloneNotSupportedException e) {
            e.printStackTrace();
        }
    }
}
  1. Define Wrapper Classes in Java?

Wrapper class is a mechanism which contains primitive data types of class and it converts to primitive data type to object and object to primitive data type by using Autoboxing and unboxing technique.
For example Primitive data type ‘char’ and wrapper class is ‘Character’
Example 1: Autoboxing

public class InterviewTest {
    public static void main(String[] args) {
        int id = 25;
        short sh = 10;
        byte by = 15;
        char letter ='N';
        boolean tr = true;
        float fdes = 5.25F;
        double ddes = 6.27D;
        long lon = 43L;
       
        //Autoboxing
        Integer i = id;
        Short s = sh;
        Byte b = by;
        Character c = letter;
        Boolean bol = tr;
        Float f = fdes;
        Double d = ddes;
        Long l = lon;
        //print object values
        System.out.println("Integer: "+i);
        System.out.println("Short: "+s);
        System.out.println("Byte: "+b);
        System.out.println("Charater: "+c);
        System.out.println("Boolean: "+bol);
        System.out.println("Float: " +f);
        System.out.println("Double: "+d);
        System.out.println("Long: "+l);
    }
}


Example 2: Unboxong

public class InterviewTest {
    public static void main(String[] args) {
        Integer i = 25;
        Short s = 10;
        Byte b = 15;
        Character c = 'N';
        Boolean bol = true;
        Float f = 5.25F;
        Double d = 6.27D;
        Long l = 43L;
       
        //Unboxing
        int id = i;
        short sh = s;
        byte by = b;
        char letter =c;
        boolean tr = bol;
        float fdes = f;
        double ddes = d;
        long lon = l;
       
        //print primitive values
        System.out.println("int: "+id);
        System.out.println("short: "+sh);
        System.out.println("byte: "+by);
        System.out.println("char: "+letter);
        System.out.println("boolean: "+tr);
        System.out.println("float: " +fdes);
        System.out.println("double: "+ddes);
        System.out.println("long: "+lon);
    }
}
  1. Can you implement pointers in a Java Program?

No, Pointers are not available in java so, we cannot implement pointers.

  1. Define System.out.println()?

System. out. println() that prints any argument you pass and adds a new line after it. println() is responsible for printing the argument and printing a new line. System.out refers to the standard output stream.
System: this is a final class and it is found at java.lang package.
Out: it is static and public modifier field of System class and it is instance of PrintStream.
Println(): it is an instance of PrintStream class and it prints output and printing new line

  1. How to create an object in Java?

Java is Object Oriented programming language so, without creating an object we cannot execute the program.
In java we provide fives ways to create an object
1.    Using new keyword
2.    Using newInstance method of class
3.    Using newInstance method of Constructor
4.    Using clone()
5.    Using Deserilization
We use Class.forName(String className) method it returns new instance of class object

  1. How to access class data members and methods in Java?

Class data members and methods into another class by using object in java but we have Instance data members and static data members and similar to methods
Example:

class NIT {
    int id = 5;
    public void test()
    {
        System.out.println("NareshIT");
    }
}
public class InterviewTest {
    public static void main(String[] args) {
        NIT nit = new NIT();
        System.out.println(nit.id);
        nit.test();
    }
}

  1. Can we declare a static variable inside a method?

No we cannot declare a static variable inside a method and only final method is allowed.
Example:

class NIT {
    public void test()
    {
        final int t = 10;
        static String name = "Naresh"; // error
    }
}
  1. What is the difference between a static and a non-static inner class?

Nested or inner static class doesn’t need a reference of Outer class but a non static nested class or Inner class requires Outer class reference.
Example:

class NIT {
    //non static
    class Test
    {
        public void print() {
            System.out.println("NON - Static inner or nested class");
        }
    }
    //static
    static class Program
    {
        void print() {
            System.out.println("Static inner or nested class");
        }
    }
}
public class InterviewTest {
    public static void main(String[] args) {
        NIT nit = new NIT();
        NIT.Test test = nit.new Test(); // for non static inner class
        test.print();
        NIT.Program prog = new NIT.Program(); // for static inner class
        prog.print();
    }
}
  1. What is the difference between a constructor and a method?

Constructor
Constructor does not have return type and it is used to initialize the object.
Default constructor is available
Method
Method has return type if you declare void it does not return any value and we access by using object.
We don’t have default method

  1. What is the difference between java.util.Date and java.sql.Date?

Both dates are storing date and time information but java.sql.Date is used to communication of java applications with the database but java.util.Date get time and date from the system.
Sometimes we need to convert sql date into util date and vice versa based on date formate

  1. What are the inner class?

We have two types of inner classes one is static inner class and non static inner class
Inner class is defined as class provides another class inside that class or group of classes in one place it is more reliable to maintain.
Example:

class NIT {
    //static inner class
    static class Staticclass
    {
       
    }
    //Non static inner class
    class NonStatic
    {
       
    }
}
  1. What is the anonymous class?

Anonymous class is nothing but without a class name of inner class which is only create single object and a anonymous class must be defined inside another class
Anonymous class may have to create in two ways like class and interface.
Syntax:

Class Outerclass
{
    //define anonymous class
    object = new  Type(parameterlist) // parameter list is optional
{
    body
};
}


Example:

class NIT {
   
    public void test() {
        System.out.println("This is Normal class");
    }
}
public class InterviewTest {
    public void testAnonymous()
    {
        NIT nit = new  NIT() // Anonymous class
        {
            @Override
            public void test() {
                System.out.println("This is Anonymous class");
            }
        };
        nit.test(); // must be class inner class method by using object
    }
    public static void main(String[] args) {
        InterviewTest inter = new InterviewTest();
        inter.testAnonymous();
       
    }
}
  1. What is the difference between thread and process?

process takes more time to create or terminate when compared to thread because thread communication is more efficient and thread have segment of process
We have multi programs holds multiple process but each process have multiple threads.
Process involved in system calls but thread is created by API’s

  1. What is Daemon thread?

In java Daemon thread is service provider thread it provides service to the user threads and the life of the Daemon thread depends on user crated threads.
Daemon thread contains two methods setDaemon(Boolean status) and isDaemon(), if user thread converts to Daemon thread use setDaemon(true) method and if current thread to check Daemon thread or not use isDaemon() method.
Example:

public class InterviewTest extends Thread{
    @Override
        public void run() {
            if(Thread.currentThread().isDaemon())// check if the thread is Daemon or not
                System.out.println("Thread is Daemon");
            else
                System.out.println("User thread");
        }
    public static void main(String[] args) {
        InterviewTest inter = new InterviewTest();// create new thread
        InterviewTest inter1 = new InterviewTest();
        InterviewTest inter2 = new InterviewTest();
       
        inter.setDaemon(true); // first thread i.e user thread convert into Daemon
       
        inter.start();
        inter1.start();
        inter2.start();
    }
}
  1. What is the difference between user thread and Deamon thread?

A user thread can keep running by the JVM running but a daemon thread cannot keep running by the JVM.
User threads are created by application but Deamon threads are created by JVM and user threads are foreground threads ant Deamon threads are background threads
User threads are high priority and Deamon threads are low priority

  1. How can we create daemon threads?

By using setDeamon(Boolean status) method is used to create deamon threads or convert user threads into daemon thread
Example:
Test test = new Test() // user thread
Test.setDeamon(true) // create deamon thread

  1. What is the difference between notify() and notifyAll() methods?

In cache memory a group of threads are waiting for notification in the form of object, if you want notifies into one thread by using notify() method and if you want to notifies all the threads by using notifyAll() method.
According to performance notify() is better performance compares to notifyAll() method
According to risk notify() has more risk compared to notifyAll() because if any thread is missing another does not take request.

  1. What is thread pool?

Thread pool is nothing but to manage collection of threads and it provides multiple tasks to increase the performance and reduce the per task invocation overhead.

  1. What is the difference between Thread and Thread pool?

Thread pool having reuse threads because it has multiple threads but Thread class contains only one thread. We have checking process in Thread pool and no checking process in Thread.

  1. What is the lifecycle of Thread?

We have various stages in lifecycle of Thread.

    • New/ Start
    • Runnable
    • Running
    • Blocked
    • Waiting
    • Terminated
  1. What is the difference between Runnable and Callable interface?

Callable interface is checked exception so it returns value otherwise it throws exception but Runnable interface is unchecked exception so it does not return any value.
Callable interface is call() method but Runnable interface have run() method
Syntax of Runnable interface

public interface Runnable
{
  public abstract void run();
}
Syntax of callable interface
public interface Callable<E>
{
  E call() throws exception ;
}


Example for callable interface

public class InterviewTest implements Callable<String>{
    @Override
    public String call() throws Exception {
        return "Welcome to NareshIT";
    }
    public static void main(String[] args) throws Exception {
        ExecutorService service  = Executors.newFixedThreadPool(3);
        InterviewTest test = new InterviewTest();
        Future<String> thread = service.submit(test);
        System.out.println(thread.get().toString());
        //test.call();
    }
}


Example for Runnable interface

public class InterviewTest implements Runnable{
   
    @Override
        public void run() {
            System.out.println("Runnable Thread");
        }
    public static void main(String[] args) throws Exception {
        InterviewTest test = new  InterviewTest();
        Thread thread = new Thread(test);
        thread.start();
    }
}
  1. How can we handle deadlock?

There are four ways to Handling the deadlock situation
1.    Prevention
2.    Avoidance
3.    Detection and Recovery
4.    Ignorance

  1. What is the purpose of join() method?

In java join() method found in java.lang.Thread class which permits one thread to wait until the other thread to finish its execution. If more than one thread invoking the join() method, then it leads to overloading on the join() method that permits the developer or programmer to mention the waiting period.
There are three overloaded join() methods
Join() : current thread stops and goes into wait state
Syntax:
public final void join() throws InterruptedException
Join(long mls) : this method is used to current thread is goes to wait state upto specified time that is in milliseconds.
Syntax:
public final synchronized void join(long mls) throws InterruptedException, where mls is in milliseconds
Join(long mls, int nanos) : this method is used to current thread is goes to wait state upto specified time that is in milliseconds plus nano seconds.
Syntax:
public final synchronized void join(long mls, int nanos) throws InterruptedException, where mls is in milliseconds.
Example:

public class InterviewTest{
    public static void main(String[] args) throws Exception {
        Thread thread = new Thread();
        thread.start();
        System.out.println(thread.isAlive());
        thread.join();
        System.out.println(thread.isAlive());
    }
}
  1. What is Thread Scheduler?

Thread Scheduler means the JVM thread using preemptive and priority based scheduling algorithm.
All Java Threads have a priority and the thread with the height priority is scheduled to run by JVM.
In case of two threads have the same priority it follows FIFO order.

  1. What is the use of super keyword?

The super keyword is used for refers to superclass (parent) objects and It is used to call superclass methods, and to access the superclass constructor.
Example:

class NIT {
    int a = 10;
    public NIT() {
        System.out.println("Super class");
    }
   
    public void test() {
        System.out.println("test method");
    }
}
class NIT1 extends NIT
{
    //super keyword implicitly by constructor
    public NIT1() {
        super();
        System.out.println("Child class");
    }
    //super keyword explicitly by constructor
    /*
    * public NIT1() { System.out.println("Child class"); }
    */
   
    // method
    public void process() {
        super.test(); //call parent class method
        System.out.println(super.a); // call parent class variable
    }
}
public class InterviewTest{
    public static void main(String[] args) throws Exception {
        NIT1 nit = new NIT1();
        nit.process();
    }
}
  1. Can Static method be overridden?

NO, static method is not overridden in java because static method of parent class is hidden  in child class but static overloaded methods are possible but different parameters
Example:

class NIT {
    // static method of base class
    public static void test() {
        System.out.println("Base class static test method");
    }
    // Non-static method of base class
    public void display() {
        System.out.println("Base class of display non static method");
    }
}
public class InterviewTest {
    public static void main(String[] args) throws Exception {
        NIT nit = new NIT1();
        nit.test();
        nit.display();
    }
}
  1. What is classLoader?

ClassLoader in java is located at JRE(Java Runtime Environment) and it is dynamically loads java class into JVM(Java Virtual Machine). Java classes aren’t loaded into memory all at once, but when required by an application and ClassLoader loads class dynamically into memory.
By using getClassLoader() method to know classLoader loads the class or not and if any class is not available it return NoClassDefFoundError or ClassNotFoundException.
There are three types of classLoaders.

    • Bootstrap ClassLoader
    • System ClassLoader
    • Extender ClassLoader

  1. What is exception handling?

Exception handling in java is a process to handle the runtime errors by using throw and throws keywords or try, catch and finally keywords.
Java.lang.Throwable is a parent class of Java Exception
There are Checked and UnChecked exceptions in java.

  1. What is the difference between Exception and error in java?

Error is a result from system resources but all errors are comes at run time and unchecked so we cannot handle errors. Exceptions are checked or unchecked exception but we handle Exception at compile time or runtime.

  1. What is the difference between throw and throws in java?

In Java throw keyword is used to throw an exception explicitly in the code, inside the function or the block of code.
In Java throws keyword is used in the method signature to declare an exception which might be thrown by the function while the execution of the code.
Example 1: for throw keyword

public class InterviewTest {
    void test(int num)
    {
        if(num<0)
        {
            throw new ArithmeticException("number must be positive");
            //System.out.println("number must be positive");
        }
        else
        {
            System.out.println(num);
        }
    }
    public static void main(String[] args) throws Exception {
        InterviewTest nit = new InterviewTest();
        nit.test(-5);
    }
}


Example 2: for throws keyword

public class InterviewTest {
   
    int test(int q, int r) throws ArithmeticException
    {
        int div = q/r;
        return div;
    }
    public static void main(String[] args) throws Exception {
        InterviewTest nit = new InterviewTest();
        nit.test(5, 0);
       
        /*
        * try { System.out.println(nit.test(5, 0)); } catch (ArithmeticException e) {
        * System.out.println("Number cannot be divisible by zero"); }
        */
    }
}
  1. What is the difference between checked and unchecked exceptions?

Checked exceptions are compile time exceptions like IOException and SQLException but unchecked exceptions are runtime exceptions like ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException etc.

  1. How can we handle checked exception?

Checked exceptions are compile time exceptions and these exceptions are handle by using try and catch method or by using throws keyword.
Example: throws Checked Exception at compile time

public class InterviewTest {
    public static void main(String[] args) throws Exception {
        FileInputStream file = new FileInputStream("D:/input.txr"); // throws FileNotFoundException
    }
}


Example: handle checked exception

public class InterviewTest {
    public static void main(String[] args) throws Exception {
        try {
            FileInputStream file = new FileInputStream("D:/input.txr"); // FileNotFoundException
        } catch (FileNotFoundException e) {
            System.out.println("This file not found");
        }
       
    }
}
  1. What is runtimeException?

Runtime exception is a unchecked exception. Runtime exceptions are might be throw during the execution process it might not be catch.

public class InterviewTest {
    public static void main(String[] args) throws Exception {
        String name = null;
        System.out.println(name.length());// NullPointerException
    }
}
  1. What is Custom exception?

Custom Exception is nothing but user defined exceptions or own exception derived from exception class.

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

In java final is a keyword used to restrict the modification of a variable, method, or class. finally keyword is a block used to ensure that a section of code is always executed, even if an exception is thrown. finalize is a method used to perform cleanup processing on an object before it is garbage collected.

  1. What is the difference between ClassNotFoundException and NoClassDefFoundError?

ClassNotFoundException is thrown when looking up a class that is not found classpath or using an invalid name to look up a class that not found on the runtime classpath. NoClassDefFoundError occurs when a compiled class references another class that isn't on the runtime classpath.

  1. What is the use of printStackTrace() in exception handling of java?

It is used to print exception or error in console with other details like class name along with where exception occured and it if found at java.lang.Throwble class to handle exception or error.
It used to understand easy handle the exception
Syntax:
public void printStackTrace()
Example:

public class InterviewTest {
    public static void main(String[] args)  {
        try
        {
            String name = null;
            name.length();
        }catch (Throwable e) {
            e.printStackTrace();
        }
    }
}


Execution:
NullPointerException : Cannot invoke "String.length()" because "name" is null.

Scope @ NareshIT:

The Core Java Online Training program at NareshIT is a comprehensive hands-on learning experience through which the student gets exposed to front-end, middleware and back-end technologies. These phase-end projects are designed to provide practical solutions to real world problems so that the students are equipped with up-to-date skills that meet industry requirements.


Industry experts teach the program and its content is based on current market trends. You will learn about end-to-end application development that not only makes robust but also feature-laden applications.

At the end of this course, you will be awarded an industry recognized completion certificate that serves as testimony to your knowledge in Core Java development thus increasing your chances of employment.