0% found this document useful (0 votes)
11 views

Core Java Interview Questions With Answers

Uploaded by

charanshelby12
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views

Core Java Interview Questions With Answers

Uploaded by

charanshelby12
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 8

Core Java Interview Questions with Answers

Part – 1

Q. 1 What is the difference between ‘HashMap’ and ‘Hashtable’?


The main differences are:
- ‘HashMap’ is not synchronized, while ‘Hashtable’ is synchronized.
- ‘HashMap’ allows one null key and multiple null values, while ‘Hashtable’
doesn’t allow any null keys or values.
- ‘HashMap’ is generally preferred in non-thread-safe applications due to better
performance.

Q. 2 Explain the concept of Java Generics.


Generics allow you to abstract over types. They provide compile-time type safety by
allowing you to use a type as a parameter in the definition of a class, interface, or
method. This enables you to write code that can work with different data types while
detecting errors at compile time rather than runtime.

Q. 3 What is the purpose of the ‘transient’ keyword?


The ‘transient’ keyword is used to indicate that a field should not be serialized when
the object containing it is serialized. It’s useful for fields that contain sensitive or
temporary data that shouldn’t be persisted.

Q. 4 How does garbage collection work in Java?


Garbage collection in Java is an automatic process that identifies and deletes objects
that are no longer needed by the program. The Garbage Collector (GC) periodically
looks for objects that are no longer referenced by the program and frees the memory
they occupy.

Q. 5 What is the difference between ‘final’, ‘finally’, and ‘finalize’?


- ‘final’ is a keyword used to make a variable constant, a method not overridable,
or a class not inheritable.
- ‘finally’ is a block in a try-catch-finally statement that always executes,
regardless of whether an exception is thrown or caught.
- ‘finalize()’ is a method called by the garbage collector before destroying an
object to perform cleanup operations.

Q. 6 Explain the concept of method overloading and method overriding.


- Method overloading is defining multiple methods in the same class with the
same name but different parameters.
- Method overriding is redefining a method in a subclass that is already defined
in its superclass with the same signature.

Q. 7 What is the difference between ‘String’, ‘StringBuilder’, and ‘StringBuffer’?


- ‘String’ is immutable.
- ‘StringBuilder’ is mutable and not thread-safe, offering better performance in
single-threaded scenarios.
- ‘StringBuffer’ is mutable and thread-safe, suitable for multi-threaded
environments.

Q. 8 What are anonymous classes in Java?


Anonymous classes are inner classes with no name. They are defined and
instantiated in a single expression, typically used for one-time use cases where you
need to override a method of a class or interface on the fly.

Q. 9 Explain the ‘try-with-resources’ statement.


The try-with-resources statement is a ‘try’ statement that declares one or more
resources. A resource is an object that must be closed after the program is finished
with it. This statement ensures that each resource is closed at the end of the
statement, helping to prevent resource leaks.

Q. 10 What is the difference between ‘Comparable’ and ‘Comparator’ interfaces?


- ‘Comparable’ is used to define the natural ordering of a class. It’s implemented
by the class itself.
- ‘Comparator’ is used to define custom ordering. It’s implemented in a separate
class and can be used to define multiple orderings for a single class.

Q. 11 What is the purpose of the ‘volatile’ keyword?


The ‘volatile’ keyword is used to indicate that a variable’s value may be modified by
multiple threads simultaneously. It ensures that the variable is always read from and
written to main memory, preventing thread caching issues.

Q. 12 Explain the concept of Java annotations.


Annotations are metadata that can be added to Java source code. They can be used to
provide information to the compiler, for compile-time and deployment-time
processing, or for runtime processing. Annotations can be applied to classes,
methods, fields, and other program elements.

Q. 13 What is the difference between checked and unchecked exceptions?


- Checked exceptions are checked at compile-time. The compiler requires them
to be either caught or declared in the method signature.
- Unchecked exceptions (runtime exceptions) are not checked at compile-time.
The compiler doesn’t require them to be caught or declared.

Q. 14 What is a Java Enum and when would you use it?


An Enum is a special type of class that represents a group of constants. It’s useful
when you have a fixed set of constants, such as days of the week, card suits, or
command-line flags. Enums provide type-safety and can have fields, methods, and
constructors.

Q. 15 Explain the concept of Java Stream API.


The Stream API, introduced in Java 8, provides a functional approach to processing
collections of objects. It allows for parallel execution and uses lambda expressions to
perform operations on streams of elements. Streams can be used to filter, map,
reduce, and perform other operations on collections in a more concise and often
more efficient manner.
Q. 16 What is the purpose of the ‘default’ method in interfaces?
Default methods, introduced in Java 8, allow you to add new methods to interfaces
without breaking the classes that implement these interfaces. They provide a way to
extend interfaces without forcing all implementing classes to create an
implementation of the new methods.

Q. 17 What is a Java Marker Interface?


A Marker Interface is an empty interface (no methods) used to indicate that a class
possesses certain properties. The most common examples are ‘Serializable’ and
‘Cloneable’. The presence of a marker interface tells the compiler or JVM that the
class is meant to be used in a certain way.

Q. 18 Explain the concept of Java Reflection.


Reflection is a feature in Java that allows an executing Java program to examine or
“introspect” upon itself, and manipulate internal properties of the program. It’s a
powerful tool that can be used for examining or modifying the runtime behavior of
applications.

Q. 19 What is the difference between ‘++i’ and ‘i++’?


- ‘++i’ (pre-increment) increments the value of i and then returns the
incremented value.
- ‘i++’ (post-increment) returns the current value of i and then increments it.
- The difference is noticeable when the value is used in an expression.

Q. 20 What is the purpose of the ‘synchronized’ keyword?


The ‘synchronized’ keyword in Java is used to create synchronized code blocks or
methods. It ensures that only one thread can execute a synchronized block of code or
method at a time, preventing race conditions and ensuring thread safety in concurrent
programming.

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. 3 Describe the Fork/Join framework in Java and its use cases.


The Fork/Join framework, introduced in Java 7, is an implementation of the
ExecutorService interface for running tasks in parallel. It’s designed for work that
can be broken into smaller pieces recursively. The framework uses a work-stealing
algorithm where free threads try to “steal” work from other threads’ queues. It’s
particularly useful for problems that can be solved using divide-and-conquer
algorithms, like sorting large arrays or matrix multiplication.

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. 10 What are the differences between ‘WeakReference’, ‘SoftReference’, and


‘PhantomReference’ in Java?
These are special reference types in Java, each with different behaviors:
- ‘WeakReference’: The object it refers to can be garbage collected as soon as
no strong references to it exist.
- ‘SoftReference’: Similar to WeakReference, but the garbage collector will try
to keep the object around if memory is available. Often used for memory-
sensitive caches.
- ‘PhantomReference’: The weakest reference type. It’s enqueued only when the
object is physically removed from memory. Used for scheduling post-mortem
cleanup actions.

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. 18 What are the differences between synchronized methods and ReentrantLock in


Java?
While both are used for synchronization, ReentrantLock provides more flexibility:
- ReentrantLock allows for non-block-structured locking, unlike synchronized
methods.
- ReentrantLock provides a fairness option to prevent thread starvation.
- ReentrantLock allows for timed and interruptible lock waits.
- ReentrantLock can be used with multiple Condition objects for more complex
synchronization scenarios.
However, synchronized methods are generally simpler to use and less error-prone
for basic synchronization needs.

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.

Q. 20 What is ahead-of-time compilation in Java? How does it differ from just-in-time


compilation?
Ahead-of-Time (AOT) compilation, introduced with Java 9, compiles Java bytecode
to native machine code before the program runs. This differs from Just-in-Time
(JIT) compilation, which compiles bytecode to native code at runtime. AOT
compilation can:
- Improve startup time by eliminating initial JIT compilation
- Reduce memory usage by avoiding the need for JIT compilation data
structures
- Provide more predictable performance in short-running applications
However, AOT compilation loses some of the platform independence of Java and
can’t perform some optimizations that JIT can do based on runtime information.

You might also like