Java interview questions and answers for 2024

It takes some grind to ace a Java interview. So, how will you swim through your advanced java interview questions? Or, how will you find the bright minds who can answer core java interview questions like they were primary math questions? Whether you are an experienced Java developer or a recruiter seeking the best Java developers, we encourage you to go through the following docket of Java interview questions. We hope it will help you find your dream job or dream candidate.

Java interview questions and answers for 2024

Last updated on Apr 14, 2024

Are you well-prepared for your next Java interview? or are you a hiring manager looking out for the right talent for your Java project, we have got you covered with a comprehensive list of Java questions to help consolidate your knowledge and concepts of Java.

Java is one of the programming languages that are very high in demand. Many applications are built and maintained by this incredible language, more reason for anyone to invest time in learning and developing their skills. And so, there has been a rapid growth in the number of Java development companies looking to hire the best Java developer
Below, are some of the most commonly asked Java interview questions and answers related to Java from which both developers and companies can benefit from.

This blog will give you a guide in preparation of interviews for elite US companies and help you to know which parts of the language you should develop in-depth knowledge in from beginner-friendly questions to the most advanced ones.

Basic Java interview questions and answers


List some important features of Java.

One of the commonly asked Java coding interview questions is about the features of the language. Some important Java features are as follows:

Ease of learning: Java is considered to be an easy-to-learn and understand language.

Security: Java is a secure language. The applications developed using this language are virus and tamper-proof.

OOP: OOP means Object-Oriented Programming Language. While Java is not considered to be purely object-oriented, the inclusion of features such as data abstraction, inheritance, and data-encapsulation, makes Java an object-oriented programming language. Thus, as such, everything in Java is considered an object.

Independent Platform: This is an important Java feature. Java does not depend on any specific platform and as long as the system has JRE installed, Java bytecode will be interpreted.


Name the types of memory allocations in Java.

Another popular Java interview question is about memory allocation. Five important types of memory allocations in Java are - Heap memory, Class memory, Native method stock memory, Stack memory, and Program-counter memory.


As a language, Java is considered platform-independent. Why?

Java is considered to be platform-independent because it does not depend on any hardware or software. When the Java programmer compiles Java code, the compiler converts the code into bytecode that can be run on different platforms. The only constraint is that the platform must have JRE (runtime environment) or Java Virtual Machine (JVM) installed on it. Answering this Java interview question can help the interviewer understand your depth of experience.


What is data-encapsulation in Java?

Data-encapsulation in Java is the process of hiding the variables (data) and the code applied to the data in a single unit. It is a significant feature of object-oriented programming. This helps Java developers to isolate different objects from each other and to create modules for each. By this, all objects would have their own behaviors, attributes, and functions. It prevents data or object mixing, hides data, enhances security.


What are wrapper classes in Java?

Java, as a programming language, supports primitive data types. Wrapper classes help convert these primitive data types into objects or reference types and vice versa. Thus, the wrapper classes are so named because they ‘wrap’ these data types into identifiable objects of the specific data classes the primitive data types belong to. This Java interview question can help the interviewer assess whether you are comfortable using both old and new data types.


What are constructors in Java?

In Java, constructors can be understood as a block of codes applied to an object to initialize it. It can be understood as a special method for initializing an object. Constructors are called when a class instance is created such as creating an object using the new() keyword. When a class does not contain a constructor, a default constructor, provided by the Java compiler, is automatically called.

There are two types of Java constructors - default and parameterized. When no parameters are defined, the constructor is called a default constructor. When specific parameters are defined for a constructor, it is called a parameterized constructor. While you may be using the Java programming language for some time, this Java interview question shows the interviewer that you know the technicalities too.


Why is Java not considered to be purely object-oriented?

Java supports primitive data types such as boolean, int, byte, long, float, etc. An object-oriented language must only support objects. However, the primitive data types are not objects, hence Java is not considered to be purely object-oriented.


Does Java use pointers? If not, why?

No, unlike C++, Java doesn’t use pointers. Java’s main focus is simplicity. The use of pointers complicates the process, especially for new java programmers. The use of pointers can also lead to possible errors. Moreover, pointers grant direct access to memory and thus, compromise security. By excluding pointers from Java, a certain amount of abstraction is achieved. Java has automatic Garbage Collectors, the use of pointers can slow down the garbage collection process. This advanced Java interview question deals with the intricacies of the language and answering it can help set you apart from other candidates.


Can you override static methods in Java?

No. While it is possible to hide the parent static method with a static method of the same signature class, this is not called overriding in the strict sense. This is because, during the run-time, no polymorphism can take place.


What do you understand about ClassLoader in Java?

ClassLoader is an integral element of the JRE (Java Runtime Environment). The function of the ClassLoader is to dynamically load Java classes directly to the JVM (Java Virtual Machine) during program execution, without notifying the Java run time system. The file to be executed is first loaded by ClassLoaders. Bootstrap, Extension, and Application are the ClassLoaders in Java. This is an advanced Java interview question and answering it can establish your expertise.


What are the prospects of session management in servlets?

A session is any ongoing random conversation between a client and the server. The communication between the two is composed of requests and responses from both sides. There are several ways of managing a session. Applying cookies, using session management API, authenticating the user, hidden fields in HTML, and rewriting URL are some ways of session management. However, the most common way of managing a session is using a session ID when the communication between a client and the server takes place. This Java interview question shows your application orientation to the client.


What is the JIT compiler in Java?

With the help of JIT or a Just-in-time compiler, Java programmers can enhance the Java applications’ performance. This is achieved in a runtime environment by compiling bytecode to the code of the native machine. As a result, the compilation time for running the code reduces. In essence, the JIT compiler translates the source code to a code that can be executed by the machine.

Java programs contain machine-neutral bytecodes that can run on any machine with JVM. When a Java program is run, it accesses the class files, interprets the bytecode, and performs the relevant computation. However, during the processing, extra memory and processor are used which compromise the speed. With the help of the JIT compiler, the speed and performance of the program can be improved.


Highlight the importance of Java as a language.

Java is a very secure programming language as it is hard to bug or tamper with. It is also very easy to learn and comprehend when developing applications. Most importantly, Java is a self-dependent language that runs on its own JRE platform.


Why is Java considered to be a platform-independent language?

Java is considered platform-independent as it does not depend on any software or hardware. However, it is flexible enough to be run on different platforms with the condition that the platform has a JRE environment installed on it.


Can you explain what you understand by the term Inheritance?

The term inheritance occurs when one class in a code extends to another. This means that codes used in one class can be reused in another class.


What is the purpose of encapsulation?

The purpose of encapsulation is to maintain code and protect the code from others.


What is the solution where multiple inheritances is not possible to achieve?

The solution to this problem is to use interfaces instead of inheritance. Interfaces allow a class to define multiple behaviors without the need to extend multiple classes.


What is a constructor in Java?

A block of code used to initialize an object is called a constructor. The constructor must share the same name as the class and it has no return type. Default and parameterized constructors are the two types of constructors.


Write a function that takes two numbers as input and returns the output.

Image 27-01-23 at 3.01 PM_2_11zon.webp

Tired of interviewing candidates to find the best developers?

Hire top vetted developers within 4 days.

Hire Now

Intermediate Java interview questions and answers


What is the difference between the creation of a string using new() and that of literal?

A new object is created when using new() whereas using literal, the object already existing might return with the same name.


What is the importance of synchronization?

Synchronization helps to execute threads one after another. It also prevents memory constituency errors due to shared access methods.


Does Java use Pointers and give a reason?

Java does not use pointers. This is because they are not safe and can increase the complexity of the program. Pointers are the exact opposite of Java’s simplicity.


How is an object in Java created?

A real entity that has a state and behavior is called an object. It is created using the new keyword. State, identity, and behavior are some of the characteristics of an object created.


What is OOP?

OOP is an abbreviation for Object-Oriented Programming. It is a model where programs are organized around objects rather than functions and logic. Its main focus is on objects more than using logic and is mainly preferred for large and complex codes.


What is Double Brace Initialization?

Double Brace Initialization is a technique that combines an anonymous inner class with an initialization block in order to initialize collections and improve code readability.


Define an Association.

An association can be defined as a relationship between two or more that have no ownership over another.


What is a Singleton class in Java?

A singleton class is a class that is capable of possessing only one object at a time.


Define a Java string pool.

The Java string pool is a repository of strings stored in the Java virtual machine (JVM). The pool stores only one instance of each literal string.


What is the difference between JVM and JRE?

JRE has class libraries and other JVM files however, it does not have any tools for Java development such as a debugger and compiler. While JVM has a Just In Time(JIT) tool to convert all the Java codes into compatible machine language.


What is method overloading in Java?

It's a process of creating multiple method signatures using one method. There are two ways of achieving this i.e changing the return type of the method and varying the number of arguments.


What are the five stages of a thread’s lifecycle?

The stages of a thread’s lifecycle are as follows:

Newborn state- This is where a new thread is created. In this newborn state, the code has not been run or executed as yet.

Runnable state- A thread that is ready to run is put into the runnable state. The code may be running or ready to run at any given time but at this stage, the thread scheduler provides the time for the thread to run.

Running state- This stage is when the thread receives a CPU moving from the runnable to the running state.

Blocked state- When the thread is inactive for a period of time temporarily, the thread is said to be in a blocked state.

Dead state- Also known as the terminated state. This is when the thread has either finished its job and exists or when some unexpected event occurs such as a segmentation fault.


Define what is enumeration in Java.

Enumeration also known as enum, is an interface in Java. It allows the sequential access of the elements stored in the collection.


Can you define Java packages and their significance?

Java packages can be defined as a collection of classes and interfaces which are bundled together while they relate to one another. It also helps developers to group a code for reuse and after being packaged it can be imported in other classes for repurposing.


What is JPA?

JPA stands for Java Persistence API. It enables developers to create the persistence layer for desktop/ web applications.


Why is Java considered dynamic?

Java is designed to adapt to any environment that is evolving. Its program has a large amount of information that is used to solve or access objects in real-time.


What are the steps involved when connecting to a database in Java?

Steps needed to connect to a database in Java are as follows:

  • Registering the driver class
  • Creating connection
  • Creating statement
  • Executing queries
  • Closing connects


How is an object serialized in Java?

To convert an object, an interface with the name serializable is implemented by the class.
All the objects of a class implementing a serializable interface get serialized and their state is saved in the byte stream.

Tired of interviewing candidates to find the best developers?

Hire top vetted developers within 4 days.

Hire Now

Advanced Java interview questions and answers


What is the difference between an array and a vector?

An array groups data of the same primitive type and is static, while vectors can hold data of different types. Vectors are dynamic though.


How is garbage collection done in Java?

Garbage collection in Java is done automatically by the Java Virtual Machine (JVM) at runtime. The JVM uses a garbage collection algorithm to identify and reclaim memory from objects that are no longer in use.


How do you create a copy of an object?

To create a copy of an object in Java, you can use the clone() method of the Object class. This method creates a shallow copy of the object, meaning that only the object's references are copied, not its values.


Outline the difference between queue and stack.

The main difference between stack and queue is that stack is based on LIFO (Last in first out) while a queue is based on FIFO( First in first out) principle. Both are used as placeholders for the collection of data.


During program compilation, what type of exceptions are caught?

Checked exceptions can be caught during the time of program compilation. The checked exceptions must be handled by using the try catch block in the code to successfully compile the code.


How are destructors defined in Java?

Java has its own garbage collection mechanism which destroys automatically objects when they are no longer referenced. Hence no destructors need to be defined.


Is it possible to find the actual size of an object on the heap?

Yes, it is possible to find the size of an object on the heap in Java. The object size can be calculated by calling the Object.getSize(Object)) method.


Define local class in Java.

When a new class inside a particular block is defined, it's called a local class. Such a class is not usable outside the block where it is defined.


Which API for operations on a set of objects is provided by Java?

Java supplies a collection of APIs which provide useful methods to be applied to a set of objects. Examples of classes provided include TreeSet, HashMap, and ArrayList.


What is Final keyword in Java?

The final keyword in Java is used to indicate that a variable, method, or class cannot be changed or overridden. It is used to create constants that cannot be changed, and to prevent a method from being overridden by a subclass.


State the difference between float and double variables.

Float only takes 4 bytes in memory while double takes twice the bytes as that of a float in memory. Double is also a double-precision decimal number while float is a single-precision floating-point decimal number.


How do you create threads in Java?

Threads can be created in two ways, by either extending the thread or by implementing the runnable interface.


Explain Out Of Memory Error in Java.

This error occurs when JVM runs out of memory. OutOfMemoryError is the subclass of Java.lang


What is exception propagation?

If an exception is not caught, it is thrown from the stack and falls down the call stack to the previous procedure. If then it is not caught there, it will fall back again to the previous function. The process repeats until caught or the call stack reaches the bottom.


Define JCA in Java.

JCA is an abbreviation of Java Cryptography Architecture and is used by developers to combine it with security applications. It, therefore, gives a platform and provides architecture and application programming interfaces that enable encryption and decryption.


What is Spring in Java?

It is an application framework in Java and inversion of control containers of Java. It creates enterprise applications in Java.


What does the lifecycle of an applet include?

The applet lifecycles include the following:

  • Initialization
  • Start
  • Stop
  • Destroy
  • Paint


What is Late Binding?

Late binding is also known as dynamic binding or run-time binding. Late Binding happens when the method’s code segment is unknown until it is called during the runtime.


Explain the reason why the delete function is faster in the linked list than in an array.

The function is faster in Java as the user needs to make a minor update to the pointer value so that the node can point to the next successor in the list.


Define a Daemon Thread.

It is a thread with the least priority. It is designed to run in the background during Garbage Collection in Java


What is the difference between >>> and >> operators?

Operator (>>) does the job of shifting sign bits while operator ( >>> ) out the zero-filled bits.


What are Java’s IDEs?

Eclipse and NetBeans are the two popular Java IDEs.


Define Polymorphism.

Polymorphism in Java is when we have many forms/classes related to each other by inheritance. A single object can refer to the sub and super class depending on the reference type which is called polymorphism’


List all the interfaces that are available in the collections.

These include:

  • Collection
  • List
  • Set
  • Map
  • Sorted Set
  • Sorted Map
  • Queue


Explain what is Ordered in collections.

lt means the values that are stored in a collection are based on the values that are added to the collection.


Define the term finally block.

A finally block in Java is a block of code that is always executed after a try/catch block, regardless of whether or not an exception has been thrown.


List the different types of Garbage Collectors in Java.

These are the different types of collectors:

  • Serial Garbage Collector
  • Parallel Garbage Collector
  • CMS Garbage Collector
  • G1 Garbage Collector


Explain the difference between System.out and System.err.

System.out is used to display messages and results while System.err is used to display error messages.


Define FailFast iterator.

FailFast iterators do not allow modifications or changes or the Java collections. This implies that they fail when the latest element is added to a collection or an element gets removed from the collection.


Explain the meaning of the term aggregation.

The term aggregation refers to the relationship between two classes. This “has” and “whole” is the most specialized version of an association relationship as it contains the reference to another class.


What is the difference between Java and C++ in terms of language compatibility?

C++, which is based on the C programming language, is compatible with most other high-level languages whereas Java is not compatible with C++.


What is a Copy Constructor in Java?

A Copy Constructor is a constructor that initializes an object through another of the same class.


Define Object-oriented paradigm.

It is a paradigm that is based on the concepts of objects. It contains data that is in the form of fields, and regulations, that are in the form of procedures. Its main feature is that the object’s procedure can access and often modify the data fields.


How do you implement a singleton class?

Firstly, you need to make sure that the class has only one object and secondly, your classes must have global access to that object


Define the term ‘this’ keyword in Java.

The term is a particular word designed as a reference keyword. It is used to refer to the current class properties like method, variable, instance, and constructors


Give the reason why generics are used in Java.

Generic methods and classes help programmers to specify a single method declaration and related types with an available class declaration.


How do you handle exceptions in Spring MVC Framework?

Spring MVC has two ways to handle exceptions:

XML Configuration: The user can use the SimpleMappingExceptionResolver in Spring’s application file and map the exception.

Exception Handler: In this kind of exception handling, the user gets the @ExceptionHandler annotation type used to annotate a method to handle exceptions.


How does a single try block and multiple catch blocks co-exist in a Java Program?

One or more catch blocks can follow a try block, though each catch must have a unique exception handler. Multiple tasks can now be performed using the Java multi-catch block.


When do you use the “super” keyword?

The super keyword often referred to as parent class can be used when there are the same fields in both parent and child classes to access data members of the parent class.


What is the difference between interface and abstract classes?

The interface has only abstract methods in it whereas an abstract class can have both abstract and non-abstract methods.


Outline the difference between shallow and deep copy in Java.

In the case of deep copy, both primitive data types and object references are copied whereas in the shallow copy only primitive data are copied.


Highlight the difference between the ‘throws’ and ‘throw’ keywords in Java.

Throws can be used to declare multiple exceptions whereas throw can throw one exception at a time.


Explain how not to serialize attributes of a class in Java.

One approach to not allow serialization of attributes of a class is by using writeObject () and readObject() methods in the subclass and throwing a not serializable exception.


Explain how the infinite loop is declared in Java.

An infinite loop can be declared by breaking the logic in the instruction box.


What are the reasons behind making strings immutable in Java apart from security?

The reasons for making the string final would be to destroy its immutability while also assisting in stopping others from trying to extend it. Strings will then be cached in the string pool, making them immutable.


Highlight the differences between final, finally, and finalize keywords.

Final is used to limit the scope of classes, variables, or methods. Finally is used to execute the code within a block without catching any exceptions. Finalize is used to invoke the code that performs garbage collection when an object is no longer in use.


Explain what is meant by Priority Queue.

A priority queue in Java is a specific kind of queue that holds elements that have an associated priority.


What a Checked Exception is?

Checked Exceptions are a type of Exception that the compiler checks for during the compilation process.


Clarify the difference between the start() and run() methods in the thread class.

Start() method creates a new thread, while the code inside run() executes in the new thread.


State the disadvantage of synchronization.

It is not recommended to implement all methods. This is because if one thread accesses the synchronized code then the next thread will have to wait. This will end result in slow performance.


Outline the purpose of transient variables.

Transient variables are not part of the serialization process. The values of the transient variables are set to a default value during deserialization. It is therefore not used with static variables.


Outline the purpose of a Volatile variable.

Volatile variables are always read from the main memory and not from the thread’s cache memory. This is used during synchronization and is applicable to variables only.


Define SerialVersionUID.

When an object is serialized, the object is stamped with a version ID number for the class object. The ID is called SerialVersionUID. It is used during deserialization to verify the sender and receiver that are compatible with serialization


What is the difference between Serialization and Deserialization in Java?

Serialization is the process which is used to convert objects into byte stream whereas Deserialization is the opposite process where we can get the objects back from the byte stream.


What is the sleep() method in a thread?

The sleep method is used to sleep the currently executing thread for a given amount of time. Sleep is used to delay the execution period because once the thread wakes up it can move to the runnable state.


List ways to stop a thread in Java.

These are:

  • Blocked
  • Waiting
  • Sleeping


State the difference between notify() and notifyAll() methods in Java.

Notify() is used to send a signal to wake up a single thread in the waiting pool while notifyAll() sends the signal to wake up all the threads in the waiting pool.


List the Exception handling keywords in Java.

The keywords for exception handling are:

  • try
  • catch
  • finally


Explain the difference between TreeSet and HashSet.

TreeSet maintains the elements in the sorted order. On the other hand, the elements in HashSet are inserted in random order.


Define Public and private access specifiers.

Public and private access specifiers are methods and instance variables known as members. Public members are visible in the same package as well as outside whereas private members are visible in the same classes only and not for other classes in the same packages.


Explain what the yield method of the Thread class does.

Yield() method moves the thread back to the runnable state only not to sleep(), wait(), or block but allowing other threads for execution.


Explain the wait() method.

This method is used to make the thread wait in the waiting pool. Once executed during the thread execution then instantly the thread gives up the lock on the object and goes into the waiting pool.


List the different authentications in Java Servlets.

These are:

  • Basic authentication
  • Form-based authentication
  • Digest authentication
  • Client certificate authentication


Does Java work on a “pass by reference” or “pass by value” phenomenon?

Java works only as a “pass by value” as “pass by reference” needs the assistance of pointers. Java does not have pointers.


Explain the default values assigned to variables and instances in Java.

For a numerical value, it is O, for the boolean value, it is false and NULL value for objects.


Write a function that takes an integer as input and returns a statement that indicates whether the input value is a positive integer or negative integer.

Image 27-01-23 at 3.02 PM_3_11zon.webp


Create a function that returns the current date and time.

Image 27-01-23 at 3.02 PM (1)_4_11zon.webp


Create a Java function that finds the k-smallest element in a given array of numbers.

Image 27-01-23 at 3.03 PM_5_11zon.webp

Tired of interviewing candidates to find the best developers?

Hire top vetted developers within 4 days.

Hire Now

Wrapping up

We have listed some of the most asked Java interview questions and answers, that will help you prepare for technical interviews. Apart from the basic interview questions, it is important to develop soft skills while in the process as this will help excel increase your chances of landing your desired position.
If you feel confident and ready to solve some Java challenges, do take the Turing Java test and be counted among the best Java candidates in the global pool. Also, if you are a hirer looking out for an easier approach to hire the best talent for your Java project, you can contact Turing which helps you source,vet and manage the best Java developers remotely.

Hire Silicon Valley-caliber Java developers at half the cost

Turing helps companies match with top-quality Java developers from across the world in a matter of days. Scale your engineering team with pre-vetted Java developers at the push of a button.

Hire developers

Hire Silicon Valley-caliber Java developers at half the cost

Hire remote developers

Tell us the skills you need and we'll find the best developer for you in days, not weeks.