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

Related Courses
slide 6 to 11 of 10

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:

  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:

  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:

  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


Example 2: Unboxong

  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:

  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:

  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:

  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:

  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:


Example:

  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:

  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


Example for callable interface


Example for Runnable interface

  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:

  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:

  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:

  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


Example 2: for throws keyword

  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


Example: handle checked exception

  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.

  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:


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.