Java Interview Question & Answer
- Explain the difference between
==
andequals()
in Java. - How does Java manage memory? What is the role of garbage collection?
- What are the key differences between an abstract class and an interface?
- Explain the concept of inheritance in Java.
- What is polymorphism, and how is it implemented in Java?
- How does exception handling work in Java? What are checked and unchecked exceptions?
- Explain the purpose of the
final
,finally
, andfinalize
keywords. - How does Java achieve platform independence?
- What are the different types of class loaders in Java?
- Describe the lifecycle of a thread in Java.
Java 8 Features
- Explain the concept of lambda expressions in Java 8.
- What are functional interfaces? Provide examples.
- How does the
Stream
API work in Java 8? Provide examples of intermediate and terminal operations. - Explain the use of
Optional
in Java 8. - How does method reference work in Java 8?
- Describe the purpose and usage of
CompletableFuture
in Java 8. - What are the new Date and Time APIs in Java 8? How do they differ from the old Date API?
- Explain the purpose of the
default
andstatic
methods in interfaces in Java 8. - How can you improve performance with the
Parallel Stream
in Java 8? - What are the best practices for using lambda expressions?
Java 9 Features
- What is the Java Platform Module System (JPMS)? Explain its significance.
- How do you create a module in Java 9?
- Explain the concept of modular JARs.
- What is the purpose of the
module-info.java
file? - How does the
jlink
tool work in Java 9? - Describe the new
ProcessHandle
API in Java 9. - What improvements were made to the
Stream
API in Java 9? - How does the
Reactive Streams
API work in Java 9? - What is the
Stack-Walking API
in Java 9, and how is it used? - Explain the concept of
Private Interface Methods
in Java 9.
Java 10 Features
- What is the
var
keyword in Java 10? How does it work? - Explain the concept of local variable type inference in Java 10.
- What are the limitations of using
var
in Java 10? - How does Java 10 enhance the
Garbage Collector
? - Describe the
Application Class-Data Sharing
(AppCDS) feature in Java 10. - What are the improvements in the
Optional
API in Java 10? - Explain the purpose of the
Thread-Local Handshakes
feature in Java 10. - How does
Heap Allocation on Alternative Memory Devices
work in Java 10? - What are the changes in the
G1 Garbage Collector
in Java 10? - Describe the
Root Certificates
feature introduced in Java 10.
Java 11 Features
- What are the key features introduced in Java 11?
- Explain the new
HttpClient
API introduced in Java 11. - How does Java 11 support the
var
keyword in lambda expressions? - Describe the
Nest-Based Access Control
feature in Java 11. - How can you use the new
String
methods introduced in Java 11? - What is the
Z Garbage Collector
(ZGC) in Java 11? How does it work? - Explain the
Dynamic Class-File Constants
feature in Java 11. - How does Java 11 enhance
Flight Recorder
andMission Control
? - What changes were made to the
Epsilon
garbage collector in Java 11? - How does the new
Launch Single-File Source-Code Programs
feature work in Java 11?
Concurrency and Multithreading
- What is the difference between
synchronized
andLock
in Java? - How does the
Executor
framework work in Java? - Explain the concept of
Callable
andFuture
in Java. - How can you implement a thread pool in Java?
- What are the best practices for avoiding deadlocks?
- Explain the difference between
volatile
andAtomic
variables. - How do
CountDownLatch
andCyclicBarrier
differ? - What is the
Fork/Join
framework, and how does it work? - Describe the purpose of the
ThreadLocal
class. - How does
CompletableFuture
differ fromFuture
in Java?
Q1: Explain the difference between `==` and `equals()` in Java.
Answer:- In Java, `==` is a reference comparison operator that checks if two object references point to the same memory location. In contrast, `equals()` is a method that compares the content or state of two objects. For example, with `String` objects, `==` checks if both references are the same, while `equals()` checks if the actual string values are equal.
Q2: How does Java manage memory? What is the role of garbage collection?
Answer:- Java manages memory through the Java Virtual Machine (JVM), which allocates memory for objects in the heap. The role of garbage collection is to automatically identify and dispose of objects that are no longer referenced by the application, freeing up memory for new objects. This helps prevent memory leaks and optimizes the application's memory usage.
Q3: What are the key differences between an abstract class and an interface?
Answer:- An abstract class can have both abstract methods (without a body) and concrete methods (with a body), while an interface can only have abstract methods (in Java 7 and earlier). In Java 8 and later, interfaces can also have default and static methods. An abstract class can have instance variables and constructors, while an interface cannot. Additionally, a class can extend only one abstract class but can implement multiple interfaces.
Q4: Explain the concept of inheritance in Java.
Answer:- Inheritance in Java is a mechanism where a new class (subclass or derived class) inherits properties and behavior (fields and methods) from an existing class (superclass or base class). This promotes code reuse and establishes a hierarchical relationship between classes. The subclass can also override methods from the superclass to provide specific behavior.
Q5: What is polymorphism, and how is it implemented in Java?
Answer:- Polymorphism is the ability of an object to take on many forms. In Java, it is implemented through method overriding and method overloading. Method overriding allows a subclass to provide a specific implementation of a method that is already defined in its superclass. Method overloading allows multiple methods with the same name but different parameters within the same class.
Q6: How does exception handling work in Java? What are checked and unchecked exceptions?
Answer:- Exception handling in Java is done using try-catch blocks, where the code that might throw an exception is placed inside a `try` block, and the exception is caught and handled in a `catch` block. Checked exceptions are exceptions that must be either caught or declared in the method signature using `throws`, and they are checked at compile time. Unchecked exceptions (RuntimeException and its subclasses) do not need to be declared or caught, and they are checked at runtime.
Q7: Explain the purpose of the `final`, `finally`, and `finalize` keywords.
Answer:- The `final` keyword is used to declare constants, prevent method overriding, and prevent inheritance of classes. The `finally` block is used in exception handling to execute code that should run regardless of whether an exception is thrown or not, usually for resource cleanup. The `finalize` method is called by the garbage collector before an object is destroyed to allow the object to clean up resources, though its use is generally discouraged in favor of try-with-resources or explicit resource management.
Q8: How does Java achieve platform independence?
Answer:- Java achieves platform independence through the use of the Java Virtual Machine (JVM). Java code is compiled into bytecode by the Java compiler, and this bytecode is platform-independent. The JVM, which is platform-specific, interprets or compiles this bytecode into native machine code, allowing Java applications to run on any device or operating system that has a JVM.
Q9: What are the different types of class loaders in Java?
Answer:- Java has several types of class loaders: the Bootstrap ClassLoader, which loads core Java classes (`rt.jar`); the Extension ClassLoader, which loads classes from the extensions directory (`ext`); and the Application ClassLoader, which loads classes from the application's classpath. Additionally, developers can create custom class loaders to load classes in specific ways.
Q10: Describe the lifecycle of a thread in Java.
Answer:- The lifecycle of a thread in Java consists of the following states:
1. New: The thread is created but not yet started.
2. Runnable: The thread is ready to run and waiting for CPU time.
3. Running: The thread is executing its `run()` method.
4. Blocked/Waiting: The thread is blocked or waiting for a resource or a condition to be met.
5. Terminated: The thread has finished executing or has been stopped.
Q11: Explain the concept of lambda expressions in Java 8.
Answer:- Lambda expressions in Java 8 provide a way to
write anonymous functions in a more concise way. They enable functional
programming by allowing you to pass behavior (code) as data, which can be
executed later. A lambda expression has a simple syntax: (parameters) -> expression or (parameters) -> {statements}.
Q12: What are functional interfaces? Provide examples.
Answer:- Functional interfaces are interfaces with a single abstract
method, which can be implemented using lambda expressions. Java 8 introduced
several functional interfaces, like Runnable, Callable, Supplier, Consumer, and Predicate. For
example, Runnable is a functional interface with a single method run().
Q13: How does the Stream API work in Java 8?
Provide examples of intermediate and terminal operations.
Answer:- The Stream API in Java 8 provides a way to process collections
of data in a functional style. It supports operations like map, filter, and
reduce. Intermediate operations (e.g., filter(), map()) return
a new stream, allowing method chaining. Terminal operations (e.g., collect(), forEach()) produce
a result or side-effect and terminate the stream.
Q14: Explain the use of Optional in Java 8.
Answer:- Optional is a container class in Java 8 that represents a
value that may or may not be present. It is used to avoid null checks and
prevent NullPointerException. Methods like isPresent(), ifPresent(), and orElse() are used
to handle the value safely.
Q15: How does method reference work in Java 8?
Answer:- Method references in Java 8 provide a way to refer to methods
directly without invoking them, using :: syntax. They are often used in
place of lambda expressions when the method is already defined. There are four
types: static method references (ClassName::methodName),
instance method references (instance::methodName),
constructor references (ClassName::new), and type-specific instance method references (ClassName::methodName).
Q16: Describe the purpose and usage of CompletableFuture in Java 8.
Answer:- CompletableFuture in Java 8 is used for asynchronous programming. It
allows you to write non-blocking code by running tasks in the background and
then combining results or handling exceptions once they are completed. It
supports methods like thenApply(), thenAccept(), thenCompose(), and exceptionally() for chaining tasks and handling outcomes.
Q17: What are the new Date and Time APIs in Java 8?
How do they differ from the old Date API?
Answer:- Java 8 introduced the java.time package
with classes like LocalDate, LocalTime, LocalDateTime, and ZonedDateTime, which
are immutable and thread-safe. These APIs offer a more comprehensive and
consistent approach to date and time manipulation compared to the old Date and Calendar classes,
which were mutable and not thread-safe.
Q18: Explain the purpose of default and static
methods in interfaces in Java 8.
Answer:- Default methods in interfaces allow you to add new methods to
interfaces without breaking existing implementations. They provide a default
implementation that can be overridden. Static methods in interfaces are utility
methods that belong to the interface and cannot be overridden by implementing
classes.
Q19: How can you improve performance with the
Parallel Stream in Java 8?
Answer:- Parallel Streams in Java 8 allow you to process data in
parallel, taking advantage of multiple CPU cores to improve performance. By
using parallelStream() instead of stream(), the
stream operations are automatically divided into multiple threads, which can
significantly speed up processing for large datasets.
Q20: What are the best practices for using lambda
expressions?
Answer:- Best practices for using lambda expressions include keeping
them short and simple, avoiding state mutation within lambdas, preferring
method references when they simplify code, and using them in conjunction with
functional interfaces. Also, ensure that lambdas do not introduce readability
issues or complex logic that could be better handled with traditional methods.
Q21: What is the Java Platform Module System
(JPMS)? Explain its significance.
Answer:- The Java Platform Module System (JPMS), introduced in Java 9,
provides a way to modularize Java applications by dividing them into smaller,
manageable modules. It enhances encapsulation, improves security, and allows
for better organization of code. JPMS helps reduce the size of the runtime, as
only the necessary modules are included, and it helps to avoid conflicts by
defining clear module dependencies.
Q22: How do you create a module in Java 9?
Answer:- To create a module in Java 9, you need to create a module-info.java file in the root of your module directory. This file defines the
module's name, its dependencies (requires), the
packages it exports (exports), and the services it provides or consumes. You
then compile and package the module into a modular JAR.
Q23: Explain the concept of modular JARs.
Answer:- Modular JARs are JAR files that include a module-info.class file in their root, indicating that they are part of the Java Module
System. They can be used both as modules within a module path or as regular
JARs in the classpath. This allows them to be backward compatible with older
Java versions while supporting the new module system.
Q24: What is the purpose of the module-info.java file?
Answer:- The module-info.java file is the descriptor for a module in Java 9 and
later. It defines the module's name, dependencies, and exported packages, and
it specifies the services the module provides or uses. This file is essential
for creating modular applications and ensuring proper encapsulation and dependency
management.
Q25: How does the jlink tool
work in Java 9?
Answer:- The jlink tool in Java 9 allows you to create custom runtime
images by linking together the required modules, including the application
modules and a minimal set of JDK modules. This results in a smaller, optimized
runtime that includes only the necessary components, improving performance and
reducing the application footprint.
Q26: Describe the new ProcessHandle API in Java 9.
Answer:- The ProcessHandle API in Java 9 provides a more comprehensive
and flexible way to interact with operating system processes. It allows you to
manage and monitor processes, retrieve process information (e.g., PID, CPU
usage), and handle process termination. This API improves upon the older Process class by
offering a cleaner, more detailed interface.
Q27: What improvements were made to the Stream API
in Java 9?
Answer:- Java 9 introduced several improvements to the Stream API,
including the takeWhile(), dropWhile(), and ofNullable() methods.
takeWhile() and dropWhile() allow
you to process streams conditionally, stopping or skipping elements based on a
predicate. ofNullable() creates a stream from a single element if it is
non-null, or an empty stream if the element is null.
Q28: How does the Reactive Streams API work in Java
9?
Answer:- The Reactive Streams API in Java 9 is part of the java.util.concurrent.Flow package and provides interfaces for building
reactive, asynchronous, and non-blocking data streams. It consists of Publisher, Subscriber, Subscription, and Processor
interfaces, enabling backpressure and allowing the flow of data to be
controlled based on the consumer's capacity.
Q29: What is the Stack-Walking API in Java 9, and
how is it used?
Answer:- The Stack-Walking API in Java 9 provides a flexible and
efficient way to traverse and examine the call stack. Unlike the traditional Thread.getStackTrace(), it allows developers to lazily access stack
frames and filter or process them as needed. This API is useful for debugging,
logging, and implementing security checks.
Q30: Explain the concept of Private Interface
Methods in Java 9.
Answer:- Private Interface Methods in Java 9 allow interfaces to have
private methods that cannot be accessed outside the interface. These methods
can be used to share code between default and static methods within the same
interface, helping to reduce code duplication and improve code organization
within interfaces.
Q31: What is the var keyword
in Java 10? How does it work?
Answer:- The var keyword, introduced in Java 10, allows local
variable type inference, meaning the compiler automatically infers the variable
type based on the assigned value. This makes code more concise, as you no
longer need to explicitly declare the type of a local variable. However, var can only
be used for local variables, not fields or method parameters.
Q32: Explain the concept of local variable type
inference in Java 10.
Answer:- Local variable type inference in Java 10 allows you to declare
local variables without explicitly specifying their type. By using the var keyword,
the type is inferred from the right-hand side of the assignment. For example, var list = new ArrayList<String>(); automatically infers list as ArrayList<String>.
Q33: What are the limitations of using var in Java 10?
Answer:- The limitations of using var in Java 10 include:
- var can only be used for local variables, not for fields, method parameters, or return types.
- The inferred type must be clear and unambiguous; complex or unclear types can reduce code readability.
- It can make the code less explicit, leading to potential confusion, especially for people unfamiliar with the code.
- var cannot be used for variables that do not have an initializer, as the compiler needs the initializer to infer the type.
Q34: How does Java 10 enhance the Garbage
Collector?
Answer:- Java 10 introduced several enhancements to the Garbage
Collector, including parallel full garbage collection for the G1 Garbage
Collector, which improves its performance and reduces the time spent in full
garbage collection cycles. It also included improved logging and diagnostics
for better monitoring and tuning of garbage collection behavior.
Q35: Describe the Application Class-Data Sharing
(AppCDS) feature in Java 10.
Answer:- Application Class-Data Sharing (AppCDS) in Java 10 extends the
existing Class-Data Sharing (CDS) feature to allow application classes to be
shared across multiple JVMs. This reduces startup time and memory footprint by
enabling the sharing of class metadata, resulting in better performance for
large-scale applications.
Q36: What are the improvements in the Optional API in Java 10?
Answer:- Java 10 introduced new methods in the Optional API,
such as orElseThrow(), which provides a more explicit way to throw a NoSuchElementException when the Optional is
empty. This method is a more descriptive alternative to get() and
helps improve code readability and intent.
Q37: Explain the purpose of the Thread-Local
Handshakes feature in Java 10.
Answer:- The Thread-Local Handshakes feature in Java 10 allows JVM
operations to be executed on individual threads without stopping all threads.
This feature improves the performance of tasks like garbage collection and
thread stack management by reducing the global safepoint pauses and allowing
finer-grained control over thread execution.
Q38: How does Heap Allocation on Alternative Memory
Devices work in Java 10?
Answer:- Heap Allocation on Alternative Memory Devices in Java 10 enables
the JVM to allocate Java object heap memory on alternative memory devices, such
as NVMe or other persistent memory technologies, instead of the default RAM.
This feature is useful for systems with tiered memory configurations, allowing
more efficient use of available memory resources.
Q39: What are the changes in the G1 Garbage
Collector in Java 10?
Answer:- In Java 10, the G1 Garbage Collector was improved with the
addition of parallel full garbage collection, which allows multiple threads to
be used during the full GC phase, reducing the time required for full garbage
collection and improving overall application performance.
Q40: Describe the Root Certificates feature
introduced in Java 10.
Answer:- Java 10 introduced the inclusion of default root certificates
in the JDK, which helps developers create applications that require TLS or SSL
connections without needing to manually configure or install root certificates.
This simplifies the process of developing secure applications by providing a
ready-to-use set of trusted certificates.
Q41: What are the key features introduced in Java
11?
Answer:- Java 11 introduced several key features, including:
- The new HttpClient API for modern HTTP communication.
- Support for var in lambda expressions.
- Nest-Based Access Control for improved security and encapsulation.
- New methods in the String, Optional, Files, and Collection APIs.
- The Z Garbage Collector (ZGC) for low-latency garbage collection.
- The ability to run single-file source-code programs without prior compilation.
- Dynamic Class-File Constants for more efficient bytecode generation.
Q42: Explain the new HttpClient API introduced in Java 11.
Answer:- The new HttpClient API in Java 11 replaces the old HttpURLConnection API and provides a modern, flexible, and easy-to-use interface for
sending HTTP requests and handling responses. It supports both synchronous and
asynchronous communication, as well as HTTP/2 and WebSocket protocols, making
it more suitable for modern web applications.
Q43: How does Java 11 support the var keyword
in lambda expressions?
Answer:- Java 11 allows the use of the var keyword
in lambda expressions for explicitly declaring the types of lambda parameters.
This provides consistency with local variable type inference and can make
lambda expressions more readable by allowing the use of annotations on
parameters, which was not possible before.
Q44: Describe the Nest-Based Access Control feature
in Java 11.
Answer:- Nest-Based Access Control in Java 11 allows related classes,
such as inner classes, to access each other's private members directly. This
feature provides a more flexible and secure way to manage access between nested
classes without exposing their members to the outer world, reducing the need
for synthetic methods.
Q45: How can you use the new String methods
introduced in Java 11?
Answer:- Java 11 introduced several new String methods,
including:
- strip(), stripLeading(), and stripTrailing() for trimming whitespace more effectively.
- isBlank() to check if a string is empty or contains only whitespace.
- lines() to split a string into a stream of lines.
- repeat(int) to repeat the string multiple times.
These methods enhance string manipulation and make the code more concise and expressive.
Q46: What is the Z Garbage Collector (ZGC) in Java
11? How does it work?
Answer:- The Z Garbage Collector (ZGC) introduced in Java 11 is a
low-latency garbage collector designed to handle large heaps with minimal
impact on application performance. ZGC performs garbage collection concurrently
with application threads, aiming to keep GC pauses under 10 milliseconds, even
for very large heaps. It achieves this by dividing the heap into regions and
managing them individually.
Q47: Explain the Dynamic Class-File Constants
feature in Java 11.
Answer:- The Dynamic Class-File Constants feature in Java 11 allows the
Java class file format to contain constants that are computed at runtime rather
than being fixed at compile time. This makes it easier to implement
constant-like behavior in a more flexible manner, supporting future language
features and reducing the need for workarounds in bytecode generation.
Q48: How does Java 11 enhance Flight Recorder and
Mission Control?
Answer:- Java 11 enhances Flight
Recorder and Mission Control by integrating them more closely with the OpenJDK,
making these tools available as part of the standard JDK distribution. This
provides developers with powerful tools for profiling, monitoring, and
diagnosing performance issues in Java applications without needing third-party
tools.
Q49: What changes were made to the Epsilon garbage
collector in Java 11?
Answer:- The Epsilon garbage collector introduced in Java 11 is a "no-op"
garbage collector that does not actually perform any memory reclamation. It is
primarily used for performance testing, where developers want to measure the
impact of GC on their application or where garbage collection is not needed
(e.g., short-lived processes).
Q50: How does the new Launch Single-File
Source-Code Programs feature work in Java 11?
Answer:- The Launch Single-File Source-Code Programs feature in Java 11
allows you to run Java programs directly from a single source file without
needing to compile it separately. You can run a program using the java command
followed by the source file name, and the JVM will automatically compile and
execute it, simplifying the development process.
Q51: What is the difference between synchronized and Lock in Java?
Answer:- synchronized is a keyword in Java used to lock a method or a
block of code to ensure that only one thread can execute it at a time. The Lock
interface, introduced in Java 5, provides more flexibility than synchronized. For
example, Lock allows you to try to acquire the lock without
blocking, interrupt the lock acquisition, and implement fairness policies. Lock also
supports more advanced synchronization techniques like ReentrantLock.
Q52: How does the Executor framework work in Java?
Answer:- The Executor framework in Java, introduced in Java 5, provides
a higher-level API for managing threads. It decouples the task submission from
the execution mechanism, allowing you to manage a pool of threads efficiently.
The framework includes interfaces like Executor, ExecutorService, and classes like ThreadPoolExecutor, which
handle the creation, management, and scheduling of thread execution.
Q53: Explain the concept of Callable and Future in Java.
Answer:- Callable is a
functional interface in Java that represents a task that returns a result and
can throw an exception. It is similar to Runnable, but Callable can
return a value. Future represents the result of an asynchronous
computation and provides methods to check if the computation is complete,
retrieve the result, or cancel the task. It is often used with ExecutorService to submit tasks and retrieve their results asynchronously.
Q54: How can you implement a thread pool in Java?
Answer:- You can implement a
thread pool in Java using the ExecutorService
interface and its implementations, like ThreadPoolExecutor. You can
create a fixed-size thread pool using Executors.newFixedThreadPool(int nThreads) or a cached thread pool using Executors.newCachedThreadPool(). Once
you have an ExecutorService, you can submit tasks to the pool, and it will manage
the execution of those tasks using its pool of threads.
Q55: What are the best practices for avoiding
deadlocks?
Answer:- Best practices for
avoiding deadlocks include:
- Always acquiring locks in a consistent order across all threads.
- Minimizing the scope of locks to reduce the chances of contention.
- Avoiding nested locks, where a thread holds one lock and tries to acquire another.
- Using lock timeouts, where possible, to prevent indefinite blocking.
- Using higher-level concurrency utilities, like java.util.concurrent classes, which reduce the need for explicit locking.
Q56: Explain the difference between volatile and Atomic variables.
Answer:- volatile is a keyword used in Java to indicate that a
variable's value will be modified by different threads. It ensures that changes
to the variable are visible to all threads immediately. However, volatile does not
guarantee atomicity for compound actions like incrementing a value. Atomic
variables, like AtomicInteger, provide atomic operations, meaning they are
thread-safe and prevent race conditions when performing compound actions like
increments or compare-and-set.
Q57: How do CountDownLatch and CyclicBarrier differ?
Answer:- CountDownLatch is a
synchronization aid that allows one or more threads to wait until a set of operations
being performed by other threads completes. It is a one-time use latch that
cannot be reset once the count reaches zero. CyclicBarrier, on the
other hand, is a reusable barrier that allows a set of threads to wait for each
other to reach a common point before proceeding. Once all threads reach the
barrier, it resets, and the threads can continue.
Q58: What is the Fork/Join framework, and how does
it work?
Answer:- The Fork/Join framework in Java, introduced in Java 7, is
designed for parallel processing of tasks that can be recursively split into
smaller subtasks. It uses the ForkJoinPool, which
manages a pool of worker threads, and ForkJoinTask, which
represents a task that can be forked into smaller tasks and then joined to
produce a result. This framework is particularly useful for divide-and-conquer
algorithms.
Q59: Describe the purpose of the ThreadLocal class.
Answer:- The ThreadLocal class in Java provides thread-local variables,
which are variables that are local to the current thread. Each thread accessing
such a variable has its own independently initialized copy of the variable,
allowing threads to work with their own data without interference from other
threads. This is useful for maintaining per-thread context, like user sessions
or database connections.
Q60: How does CompletableFuture differ from Future in Java?
Answer:- CompletableFuture is an extension of the Future
interface introduced in Java 8 that provides a more flexible and comprehensive
API for asynchronous programming. Unlike Future, CompletableFuture allows you to chain multiple asynchronous tasks, handle exceptions, and
compose tasks with methods like thenApply(), thenAccept(), and thenCompose(). It also
provides better support for non-blocking operations compared to Future, which
is limited to blocking operations like get().
-------------------------------------------Happy Learning--------------------------------------------------------