Top 50 Java Interview Questions
Top 50 Java Interview Questions
–Classloader: The Classloader is the subsystem of the JVM responsible for loading class files.
You can explain that it loads all the required classes into memory when the program starts
running.
—Heap: The Heap is where objects are stored during the runtime of the program. It’s the area
of memory used for dynamic memory allocation, where Java objects and their associated data
are allocated.
—Method Area: The Method Area holds class-level information such as static variables,
constant pools, method data, and the code for methods. You should explain that it’s part of the
JVM’s memory that stores per-class structures.
—Stack: The Stack is used for storing method calls and local variables. Every time a method is
called, a new frame is created on the stack to store variables and track the method’s progress.
Each method call pushes a new frame, and when the method finishes, the frame is popped off.
—-Execution Engine: This is the component that reads and executes the bytecode of the Java
program. You should highlight that the execution engine can either interpret the bytecode line by
line or use the JIT (Just-In-Time) compiler to convert the bytecode into machine code for faster
execution.
—JNI (Java Native Interface): The JNI allows Java applications to interact with native
applications or libraries written in other languages like C or C++. This is useful when Java needs
to perform operations that depend on platform-specific features or external libraries.
It's a programming paradigm based on the concept of objects. Objects are like containers that
hold both data (fields) and code (methods). These methods operate on the data within the
object, making it easier to access and modify.
In OOP, objects are created from classes, which act as blueprints that define the structure and
behavior of the objects. This helps organize code by linking data with the procedures that
operate on it, making programs more modular and easier to manage.
Some common OOP languages include C++, Java, Python, and JavaScript. These languages
allow you to model real-world entities as objects, providing a clear and efficient way to write
complex applications.
However, since Java uses eight primitive data types — boolean, byte, char, int, float, long,
short, and double — which are not objects, Java cannot be considered a 100% object-oriented
language.
It as a form of association where each object has its own lifecycle, but there is an ownership
relationship. The child object cannot belong to any other parent object.
Aggregation helps in reusing code by creating a relationship between two classes, often
described as a ‘has-a’ or ‘whole/part’ relationship. One class contains a reference to another,
and it's said to have ownership of that class.
These kinds of technical Java questions are designed to test your depth of knowledge, so avoid
giving a purely bookish definition. Instead, mention how aggregation is useful for building more
modular and maintainable systems.
It's the root class for all non-primitive types in Java. Every class in Java either directly or
indirectly inherits from Object, making it a core part of the Java language.
The class defines important methods like equals(), hashCode(), and toString(), which are
universally used across the Java class hierarchy. By inheriting from Object, all classes gain a
common structure that supports interoperability, polymorphism, and object comparison.
Finally Finalize
Used for exception handling Protected method java.lang.object
It is a block. It is a method.
Can be followed by try-catch/ without it. Can be explicitly called from an application
program.`
It is used to clean up the resources used in Clean up the activities related to the object
the ‘try’ block. before the destruction.
An anonymous inner class is a local inner class without a name, so it cannot have a constructor.
It either extends a class or implements an interface and is defined and instantiated in a single
statement.
It’s often used to override methods and can only implement one interface at a time.
An inner class is a non-static nested class associated with an instance of the outer class and
has access to all its methods and variables.
The System class is one of the core classes in Java, and it’s marked as final, which means you
can’t extend or inherit from it. Since it doesn’t provide any public constructors, you can’t
instantiate it either. All of its methods and fields are static, and it’s mainly used to access system
resources like standard input/output, environment variables, and properties.
It's a fundamental class, and understanding its role helps when working with system-level
operations in Java.
A daemon thread is a background thread in Java, typically used for tasks like garbage collection
or logging. To create a daemon thread, you call setDaemon(true) before invoking the start()
method; otherwise, you'll encounter an IllegalThreadStateException. Daemon threads are
designed to provide support to non-daemon (user) threads. The key difference is that they don’t
prevent the program from exiting—once all non-daemon threads finish, daemon threads
automatically terminate.
These threads are useful for background tasks that don’t need to complete if the main program
finishes, optimizing performance and resource utilization. By using daemon threads, developers
can ensure that important auxiliary tasks are handled efficiently without blocking the termination
of the main application.
No, Java doesn’t support global variables. This is because global variables can lead to
namespace collisions, where multiple parts of a program might unintentionally use the same
variable name, leading to conflicts. Additionally, global variables break referential transparency,
which means functions or methods can become dependent on external states, making the
program harder to debug and maintain.
In Java, variables are typically scoped within classes, methods, or blocks, ensuring better
control over their use and preventing unintended side effects.
This explanation addresses the reasoning behind why Java avoids global variables and
demonstrates an understanding of scope and program design.
1. Define the interface: Create an interface that declares the methods available for remote
invocation.
2. Implement the interface: Provide the concrete implementation of the methods defined in
the interface.
3. Compile the interface and implementation: Use the Java compiler to compile the
interface and its implementation.
4. Compile server implementation with RMI compiler: Use the RMI compiler (rmic) to
generate the necessary stub and skeleton classes.
5. Run the RMI registry: Start the RMI registry to bind the remote objects for client access.
6. Run the application: Start the server and client applications to allow remote method
calls.
By following these steps, developers can set up remote objects and enable communication
between distributed systems using RMI. This response clearly explains the RMI development
process, focusing on the steps and purpose of each, which is what the interviewer will be
looking for.
11. Explain the differences between time slicing and preemptive scheduling?
In time slicing, each task gets a fixed amount of time (a time slice) to execute. After its slice is
over, it moves to the ready queue, and the next task runs. This method is used for non-priority
scheduling, where all tasks share CPU time equally.
In preemptive scheduling, tasks are executed based on priority. The highest-priority task runs
until it completes or is preempted by an even higher-priority task.
The garbage collector in Java is a daemon thread with low priority, running in the background. It
automatically manages memory by identifying and reclaiming unused objects, ensuring efficient
resource utilization. Since it’s a daemon thread, it doesn’t interfere with the main program’s
execution, silently freeing up memory to maintain smooth application performance.
This thread is crucial for Java's memory management, contributing to the language's efficiency
and reliability.
This version is concise, focusing on the garbage collector’s role as a daemon thread and its
importance in memory management.
This lifecycle outlines how a thread moves through different states during execution.
14. State the methods used during deserialization and serialization process.
These methods are crucial for saving and retrieving object states in Java.
A volatile variable in Java ensures that its value is always read from the main memory, not from
a thread's cache. This is crucial for synchronization because it guarantees visibility of changes
across threads. The variable is declared with the volatile keyword to indicate that its value can
be modified by external factors.
In Java, every primitive data type has a corresponding wrapper class. These classes "wrap" a
primitive value into an object, allowing primitives to be treated as objects. This is essential when
working with frameworks or collections that require objects instead of primitives.
A singleton class ensures that only one instance of the class is ever created. To achieve this,
the constructor is made private, preventing external instantiation.
Java's Throwable class provides several key methods for handling exceptions and errors.
The get() and load() methods in Hibernate are used to retrieve objects, but they behave
differently:
● get() returns null if the object isn’t found, whereas load() throws an
ObjectNotFoundException.
● get() always returns a real object, while load() returns a proxy object, which is a
placeholder for lazy initialization.
● get() immediately hits the database, but load() may delay the database hit until the
object is accessed.
● Use get() when you're unsure if the object exists, and load() when you're certain the
instance exists in the database.
In Java, local variables (declared inside methods) don’t automatically get a default value. Unlike
instance variables, which get values like 0 for numbers or null for objects, local variables must
be explicitly assigned a value before use. Both primitive types (like int) and object references
(like String) follow this rule. If you try to use a local variable without assigning it a value, the
compiler will throw an error.
This ensures that local variables are always properly initialized within the method or block where
they are used.
22. Define the class that remains superclass for each class?
The Object class is the superclass for all classes in Java. Every class, either directly or
indirectly, inherits from it. It provides essential methods like equals(), hashCode(), toString(),
and clone(), which can be used or overridden by any class.
A static method in Java belongs to the class itself, not to any specific object. This means you
can call it directly using the class name, without having to create an instance of the class. Since
static methods are tied to the class, they can access and modify static variables, which are also
class-level (not tied to individual objects).
The main advantage of static methods is their ability to work with static data members, which
makes them efficient for tasks that involve class-wide data and don’t need to interact with
instance-specific details.
Exception handling in Java is a way for the program to manage errors that happen during
runtime. It helps the program deal with these errors smoothly without crashing. When an
exception occurs, Java allows you to catch and handle it, ensuring that the program can
continue running or gracefully recover from the issue.
This mechanism is useful for maintaining the normal flow of the program, even when
unexpected events, like invalid input or missing files, cause errors during execution.
By using these mechanisms, Java ensures that errors are handled gracefully and the program
can recover or terminate safely.
Java was created by James Gosling in 1991 and has become a core technology in the IT
industry. It is widely used to build versatile, powerful applications that work across different
systems and environments.
When you create strings with double quotes, they utilize the String Pool. However, when using
the new keyword, a new string object is created outside the pool.
Collections in Java are a framework that allows you to group multiple objects into a single unit,
making data storage and management easier. The Collections Framework provides a consistent
structure for working with different types of objects, enabling operations like sorting, searching,
adding, removing, and manipulating data.
It simplifies how developers handle groups of objects by offering ready-made interfaces and
classes, ensuring more efficient and organized data management across various types of
collections, such as lists, sets, and maps.
Java Collections simplify data handling, offering a flexible and efficient way to manage groups of
objects.
● Abstraction hides internal details while exposing essential functionality to the user.
● Polymorphism allows objects to behave differently in different situations, with both
runtime and compile-time forms.
● Inheritance lets a subclass acquire properties and behaviors from a superclass,
promoting code reuse.
● Encapsulation wraps code and data together, using access modifiers to control visibility
and enhance security.
These OOP principles enable efficient and maintainable application development in Java.
An abstract class in Java is defined using the abstract keyword and can contain both abstract
(incomplete) and non-abstract (complete) methods. Abstract classes provide a way to define
common behavior while leaving some implementation details to be specified by subclasses.
Abstract classes help improve the structure, maintainability, and flexibility of Java applications.
Abstraction Encapsulation
Helps to define what an object does, Ensures that the internal state of an object is
without exposing how it performs those protected and managed safely through getters
operations. and setters.
Example: Using an interface to define a Example: Using private variables in a class and
method without revealing the internal providing public getter and setter methods to
implementation. access them.
Garbage collection in Java simplifies memory management by keeping the system free from
unnecessary objects, ensuring that only active objects consume memory.
Java is platform-independent because of the Java Virtual Machine (JVM). When a Java
program is compiled, it’s converted into bytecode, which is platform-neutral and doesn’t depend
on any specific operating system. The JVM then interprets this bytecode and runs it on any
system, whether it's Windows, Linux, or Mac.
This design supports Java's philosophy of “write once, run anywhere”, meaning that Java
programs can be written once and executed on any platform that has a JVM, without needing to
recompile the code for each operating system.
import java.util.Scanner;
In Java, the this keyword refers to the current object of the class. It helps the program
understand that you're talking about the current object's variables or methods. This is especially
useful when a method’s parameter has the same name as the class’s instance variable, so this
makes it clear you’re referring to the object’s variable.
In Java, Inheritance is a mechanism where one class, known as the subclass, inherits
properties and methods from another class, called the superclass. This allows the subclass to
reuse and extend the functionality of the superclass.
Inheritance is a powerful tool in Java, making code reusable and more maintainable.
In Java, multiple inheritance isn’t possible with classes, but interfaces solve this issue. An
interface allows a class to implement multiple behaviors, providing a form of abstraction and
loose coupling between modules. With recent Java updates, interfaces can now have default,
static, and private methods, giving them more flexibility.
Using interfaces in Java helps create more flexible and modular code.
A local variable is defined within a method, constructor, or block, and its scope is restricted to
that specific method or block. Once the method finishes executing, the local variable is no
longer accessible. These variables are not part of the object’s state and cannot be used outside
their defined block.
An instance variable, on the other hand, is declared inside a class but outside of any method.
Its scope extends across the entire class and is associated with an instance of the class. Each
object of the class has its own copy of the instance variables, and these variables represent the
object's state. They are accessible as long as the object exists, and their values can vary
between different instances of the same class.
Servlets are Java components that extend the capabilities of a web server. They run on Java-
powered web application servers and are designed to handle complex web requests. Servlets
provide benefits like high performance, scalability, portability, and security, making them a core
part of building Java web applications.
Servlet Process:
1. A user sends a request from the web browser.
2. The web server receives the request and forwards it to the appropriate servlet.
3. The servlet processes the request and generates a response.
4. The servlet sends the response back to the web server.
5. The web server then delivers the response to the browser, which displays the result to
the user.
Servlets rely on multiple classes and interfaces such as GenericServlet, HttpServlet,
ServletRequest, and ServletResponse, allowing them to interact with web requests and
responses efficiently.
An exception in Java refers to an unusual condition or event that occurs during the execution of
a program, often due to incorrect user input, programming errors, or other unforeseen issues.
When an exception occurs, it disrupts the normal flow of the program.
There are two main types of exceptions in Java:
1. Checked Exceptions: These are checked at compile time and must be either caught or
declared in the method signature.
2. Unchecked Exceptions: These occur at runtime and are typically due to logical errors
that are not caught by the compiler.
Java’s exception handling mechanism helps maintain the stability of the program by providing
ways to catch and handle these exceptions, preventing crashes.
The notify() method wakes up one randomly chosen thread from the waiting pool, while
notifyAll() wakes up all threads that are waiting.
In notify(), only one thread will proceed, leaving the rest in the waiting state. With notifyAll(), all
waiting threads are awakened, but only one will eventually get the lock, and the others will
continue waiting for their turn.
Java’s Collection Framework provides various types of lists to store and manage ordered
collections of objects. Some of the main list implementations include:
1. ArrayList: A resizable array that allows fast random access to elements. It is most
commonly used due to its flexibility.
2. LinkedList: A doubly-linked list, where each element is linked to its neighbors. It’s
efficient for insertions and deletions.
3. Vector: Similar to ArrayList but synchronized, meaning it is thread-safe.
4. Stack: A subclass of Vector, it implements a Last-In-First-Out (LIFO) stack of elements.
These lists provide different ways to manage and organize collections based on your needs,
whether you require fast access or efficient insertion and deletion.
A Priority Queue in Java extends the Queue interface and allows elements to be processed
based on their priority rather than just following the First-In-First-Out (FIFO) rule. You can
customize the priority using a Comparator or rely on the natural ordering of elements.
When you're asked if we can force Garbage Collection in Java, the interviewer is testing your
understanding of Java's memory management.
No, Garbage Collection in Java is an automatic process handled by the JVM. While you can
request garbage collection by calling System.gc() or Runtime.gc(), you cannot force it to
happen. The JVM will decide when to perform garbage collection, and there's no guarantee that
calling these methods will immediately trigger it.
An Object in Java is an instance of a class, representing real-world entities with specific state
and behavior. For example, a dog object might have states like name, breed, and color, and
behaviors like barking or wagging its tail.
In Java, an object is created using the new() keyword, which instantiates and initializes the
object. Each object has its own identity (unique existence), state (attributes or properties), and
behavior (actions it can perform).
The finally block is crucial in Java because it always executes, whether an exception is handled
or not. It comes after the try or catch block and ensures that important code, such as closing
files or releasing resources, is always run. In the JVM, the finally block is executed just before
the program terminates or a file is closed.