Core Java Interview Questions With Answers
Core Java Interview Questions With Answers
Part – 1
Part – 2
Q. 1 Explain the concept of Java Memory Model and how it relates to concurrent
programming.
The Java Memory Model (JMM) specifies how the Java virtual machine works with
the computer’s memory (RAM). It defines how and when different threads can see
values written to shared variables by other threads, and how to synchronize access to
shared variables. The JMM provides rules for happens-before relationships, which
guarantee that memory writes by one specific statement are visible to another
specific statement. Understanding the JMM is crucial for writing correct concurrent
programs and avoiding issues like race conditions and visibility problems.
Q. 2 What are Java agents and how can they be used to instrument Java code?
Java agents are a special type of class which, when added to the JVM, can intercept
applications running on the JVM and modify their bytecode. They use the
Instrumentation API provided by Java. Java agents can be used for various purposes
such as profiling, monitoring, logging, and modifying the behavior of applications
without changing their source code. They’re often used in Application Performance
Monitoring (APM) tools.
Q. 4 What is the Garbage First (G1) garbage collector, and how does it differ from other
garbage collectors?
G1 is a server-style garbage collector, targeted for multi-processor machines with
large memories. It’s designed to provide high throughput with minimal pause times.
G1 divides the heap into a set of equal-sized heap regions, each a contiguous range
of virtual memory. When performing garbage collections, G1 selects the regions
with the least live data first (garbage first). This allows it to focus on areas which
will yield the most free space, which is different from other collectors that typically
operate on the entire heap.
Q. 5 Explain the concept of Soft Leaks in Java and how to identify them.
Soft Leaks occur when objects are not garbage collected but are also not in active
use by the application. These often happen with caching mechanisms or object pools
that aren’t properly managed. While not as severe as hard memory leaks, soft leaks
can still lead to decreased performance and eventually OutOfMemoryErrors. They
can be identified through careful profiling, examining object retention, and
analyzing heap dumps. Tools like JProfiler or VisualVM can be helpful in
identifying soft leaks.
Q. 6 What are Java Flight Recorder and Java Mission Control? How are they used?
Java Flight Recorder (JFR) is a tool for collecting diagnostic and profiling data
about a running Java application. It’s a part of the JDK and has minimal
performance overhead, making it safe to use in production environments. Java
Mission Control (JMC) is a suite of tools for detailed analysis of the data collected
by JFR. Together, they provide powerful capabilities for performance analysis,
memory leak detection, and other diagnostics in Java applications.
Q. 7 Describe the process of writing a custom ClassLoader in Java and scenarios where it
might be useful.
A custom ClassLoader in Java is created by extending the ClassLoader class and
overriding its methods, particularly findClass(). The process involves:
1. Defining where to load classes from (e.g., network, database).
2. Implementing the loading logic in findClass().
3. Converting the loaded data into a Class object using defineClass().
Custom ClassLoaders are useful for:
- Loading classes from non-standard locations (like databases or over networks).
- Implementing version control for loaded classes.
- Implementing security policies by adding checks before loading classes.
- Hot-deploying classes in application servers.
Q. 8 What is the Java Native Interface (JNI)? Provide an example of when and how it
might be used.
JNI is a programming framework that allows Java code running in a Java Virtual
Machine (JVM) to call and be called by native applications and libraries written in
other languages like C, C++, and assembly. It’s used when:
- You need to access system or hardware-specific features not accessible
through Java.
- You want to use legacy code written in other languages.
- You need to perform high-performance operations that Java can’t provide.
For example, you might use JNI to access specialized hardware devices,
implement performance-critical sections in C++, or integrate with system-level
services.
Q. 9 Explain the concept of Metaspace in Java and how it differs from PermGen.
Metaspace, introduced in Java 8, replaced the PermGen (Permanent Generation)
space. Unlike PermGen, which was a fixed-size part of the heap, Metaspace is
allocated from native memory. It stores class metadata, method metadata, and other
information about loaded classes. The key differences are:
- Metaspace can grow dynamically, while PermGen had a fixed maximum size.
- Metaspace is garbage collected along with the rest of the heap, improving
efficiency.
- OutOfMemoryError due to metadata is less likely with Metaspace, as it can
use all available system memory.
Q. 11 Describe the Unsafe class in Java. What are its use cases and potential dangers?
The sun.misc.Unsafe class provides low-level, unsafe operations that can directly
manipulate memory, create objects without constructor invocation, and perform
other “unsafe” operations. It’s used internally by many Java libraries for
performance optimization. Use cases include:
- Direct memory access and manipulation
- Creating objects without invoking constructors
- Performing low-level synchronization operations
However, it’s extremely dangerous if used incorrectly, potentially causing JVM
crashes, and its use in application code is generally discouraged.
Q. 12 What is bytecode manipulation and how can it be achieved in Java?
Bytecode manipulation is the process of modifying or generating Java bytecode,
which is the instruction set of the Java Virtual Machine. It can be used to add new
functionality, optimize code, or implement aspects without modifying source code.
Libraries like ASM, Javassist, or ByteBuddy can be used for bytecode manipulation.
Common use cases include:
- Implementing Aspect-Oriented Programming (AOP)
- Adding logging or performance monitoring
- Modifying existing classes at runtime
Q. 13 Explain the concept of CompletableFuture in Java and how it improves upon the
Future interface.
CompletableFuture, introduced in Java 8, implements the Future interface and
provides a way to perform asynchronous computations. It improves upon Future by
allowing:
- Chaining of asynchronous operations
- Combining multiple asynchronous operations
- Handling errors in asynchronous computations
- Completing futures explicitly
This makes it much more powerful for complex asynchronous workflows
compared to the more limited Future interface.
Q. 14 What are the differences between ‘volatile’ and ‘atomic’ variables in Java?
Both ‘volatile’ and ‘atomic’ variables are used for concurrent programming, but they
serve different purposes:
- ‘volatile’ ensures visibility of changes to variables across threads, but doesn’t
provide atomicity for compound actions.
- Atomic variables (like AtomicInteger) provide both visibility and atomicity,
allowing for compound actions (like increment) to be performed atomically.
- Atomic variables are generally preferred for counters or similar use cases
where you need to perform compound actions atomically.
Q. 15 Describe the Reflection API in Java and provide an example of when it might be
used.
The Reflection API allows Java programs to examine or modify the runtime
behavior of applications running in the JVM. It can be used to:
- Inspect classes, interfaces, fields, and methods at runtime
- Instantiate objects and invoke methods at runtime
- Modify field values and invoke methods on objects
It’s commonly used in frameworks (like Spring for dependency injection), IDEs,
and debugging tools. For example, you might use Reflection to create a generic
object mapper that can work with any class, or to implement a plugin system where
you can load and use classes that aren’t known at compile time.
Q. 16 What is the Java Module System introduced in Java 9? How does it change
application development?
The Java Module System, also known as Project Jigsaw, introduced a new level of
abstraction above packages. Key features include:
- Improved encapsulation: Modules explicitly declare what they export and what
they require.
- Better dependency management: Dependencies are clearly defined at the
module level.
- Improved performance: The JVM can optimize based on module information.
- Scalability: It allows the JDK itself to be modularized.
This changes application development by encouraging more modular design,
improving encapsulation, and potentially reducing the size of deployments through
custom runtime images.
Q. 17 Explain the concept of Reactive Programming in Java. What are its benefits and
challenges?
Reactive Programming is a programming paradigm oriented around data flows and
the propagation of change. In Java, it’s often implemented using libraries like
RxJava or Project Reactor. Benefits include:
- Better handling of asynchronous operations
- Improved responsiveness in applications
- Built-in error handling mechanisms
- Backpressure handling for dealing with fast producers and slow consumers
Challenges include a steep learning curve and potential complexity in debugging
and testing reactive code.
Q. 19 Describe the process of writing a custom annotation in Java and provide an example
use case.
Creating a custom annotation involves:
1. Defining the annotation interface with @interface.
2. Specifying retention policy, target, and other meta-annotations.
3. Defining annotation elements (methods in the annotation interface).
4. Implementing the annotation processor if compile-time processing is needed.
Example use case: Creating a @Loggable annotation that, when applied to methods,
automatically logs method entry and exit, along with parameters and return values.
This could be implemented using aspect-oriented programming or bytecode
manipulation.