Java_InterviewQuestion_LinkedIn_JavaCommunity
Java_InterviewQuestion_LinkedIn_JavaCommunity
Q1. What are the data types in Java? Java has two types of data
types:
1. Primitive Data Types: These include byte, short, int, long, float, double,
char, and boolean. They store simple values and are not objects.
2. Non-Primitive Data Types: These include String, Array, Class, and
Interface. They are derived from primitive data types and provide
more functionalities.
Java arrays are fixed indynamically. Q4 size. However, ArrayList (from the
Java.util package) provides a dynamic array implementation where elements
can be added or removed dynamically.
The Java Virtual Machine (JVM) is a part of the Java Runtime Environment
(JRE). It is responsible for executing Java bytecode by converting it into
machine code specific to the operating system.
Function overloading allows multiple methods to have the same name but
different parameter lists. The compiler differentiates them based on the
number or type of parameters.
Example:
Q11. What is the difference between the throw and throws keywords
in Java?
A singleton class ensures that only one instance of the class exists throughout
the application's lifecycle. It is implemented using a private constructor, a
static instance variable, and a public static method that returns the single
instance. The most common way to create a singleton class is using the lazy
initialization or eager initialization approach.
No, a try block does not necessarily need a catch block. It can be followed by
either a catch block, a final block, or both. A catch block handles exceptions
that may arise in the try block, while a final block ensures that certain code
(such as resource cleanup) is executed regardless of whether an exception
occurs.
The super keyword in Java is used to refer to the parent class. It can be used
to:
1. Try block: Contains the code that might generate an exception.
2. Catch block: Handles the exception and defines what should be done
when an error occurs.
3. Finally block: Executes regardless of whether an exception occurs or
not, often used for resource cleanup (e.g., closing files or database
connections).
1. Bootstrap ClassLoader: Loads core Java classes from rt.jar and other
essential libraries. It is implemented in native code and does not have
a Java class representation.
2. Extension ClassLoader: Loads classes from the JRE/lib/ext directory or
any other specified extension directories. It is implemented as
sun.misc.Launcher$ExtClassLoader.
3. System (Application) ClassLoader: Loads application classes from the
classpath (defined by CLASSPATH, -cp, or -classpath options). It is a
child of the Extension ClassLoader.
No, private methods cannot be overridden because they are not accessible
outside their class. If a subclass defines a method with the same name, it is
treated as a separate method rather than an override.
1. New: The thread is created but has not started executing.
2. Runnable: The thread is ready to run and waiting for CPU allocation.
3. Blocked: The thread is waiting for a resource or lock to be available.
4. Waiting: The thread is indefinitely waiting for another thread to notify
it.
5. Timed Waiting: The thread waits for a specified time (e.g., using
Thread.sleep()).
6. Terminated: The thread has completed execution or stopped due to an
error.
A memory leak occurs when objects that are no longer needed are not
garbage collected because they are still referenced somewhere. This can
cause excessive memory consumption and slow down the application.
JDK > JRE > JVM – JDK includes JRE, and JRE includes JVM.
JDK is for developers, while JRE is for users running Java applications
Q38. What is the difference between ArrayList and Vector?
The Java Memory Model (JMM) defines how threads interact with memory
and ensures visibility, ordering, and atomicity of shared data in a
multi-threaded environment.
A static method in Java belongs to the class, not instances. It can be called
using the class name without creating an object.
class Example {
static void display() {
System.out.println("Static Method");
}
}
Example.display(); // Call without creating an object
Q48. What are Java 8 Streams?
Assertions are mainly used for debugging and testing purposes to detect
logical errors early in the development process.
The hashCode() method generates a unique integer value (hash code) that
represents an object’s contents. It is primarily used in hash-based collections
like HashMap, HashSet, and Hashtable for efficient storage and retrieval. A
properly implemented hashCode() ensures better performance in
hashing-based operations.
They start with @ (e.g., @Override, @Deprecated) and are used for
configuration, code documentation, validation, and runtime processing.
Annotations enhance code organization and facilitate frameworks like Spring
and Hibernate.
The BitSet class represents a sequence of bits that can grow dynamically. It
provides efficient bitwise operations such as setting, clearing, flipping, and
checking bits. It is used for memory-efficient handling of binary data, such
as flags, filters, and permission settings.
The Java String Pool is a memory optimization technique where the JVM
stores string literals in a common pool to avoid redundant allocations. When
a new string literal is created, the JVM checks the pool first; if the string
exists, it reuses the reference instead of creating a new object. This
conserves memory and enhances performance.
Example:
String str1="Hello";
// "Hello" will be stored in String Pool
// str1 will be stored in stack memory
1. Path specifies the location of system executables like Java and javac.
2. Path is used by the operating system, while Classpath is used by the
JVM.
3. The path is set via the PATH environment variable, whereas Classpath
is set using CLASSPATH or -cp option.
4. Example: set PATH=C:\Java\bin (Path), set
CLASSPATH=C:\libs\myLib.jar (Classpath).
● Heap Memory: Stores objects and data that need to persist throughout
the program. Managed by the JVM’s garbage collector.
● Stack Memory: Holds method call frames and local variables. It
manages method execution and automatically deallocates memory
when a method exits.
Key Points:
● Map: Stores key-value pairs and allow fast retrieval based on keys (e.g.,
HashMap).
● Queue: Stores elements in a specific order (FIFO, Priority-based, etc.),
designed for processing elements sequentially.
Q69. What is the difference between LinkedHashMap and
PriorityQueue?
Q76. What are the main differences between Array and Collection?
Example:
(a, b) -> a + b
Example:
● If two objects are equal according to equals(), they must have the
same hashCode().
● However, two objects with the same hashCode() may not necessarily
be equal.
● Properly overriding both methods ensures correct behavior in
hash-based collections like HashMap and HashSet.
How It Works:
1. Segmented Locking (Java 7 and earlier) – The map was divided into
segments, reducing lock contention.
2. CAS (Compare-And-Swap) & Fine-Grained Locking (Java 8+) –
Instead of segments, it uses locks at bucket level and CAS operations
for updates.
3. Bucket-Level Synchronization – Write operations lock only the
affected bucket, allowing parallel updates.
4. No Lock for Reads – Most read operations (get()) are lock-free,
ensuring high performance.
5. Improved Scalability – Reduces contention, making it efficient for
multi-threaded environments.
Key Benefits:
How It Works:
6. Segmented Locking (Java 7 and earlier) – The map was divided into
segments, reducing lock contention.
7. CAS (Compare-And-Swap) & Fine-Grained Locking (Java 8+) –
Instead of segments, it uses locks at bucket level and CAS operations
for updates.
8. Bucket-Level Synchronization – Write operations lock only the
affected bucket, allowing parallel updates.
9. No Lock for Reads – Most read operations (get()) are lock-free,
ensuring high performance.
10.Improved Scalability – Reduces contention, making it efficient for
multi-threaded environments.
Key Benefits:
How It Works:
False sharing occurs when multiple threads modify variables that reside in
the same CPU cache line, causing unnecessary cache invalidations and
performance degradation.
To handle OutOfMemoryError:
How It Works:
How It Works:
1. Each thread gets a small, preallocated space in the Eden space.
2. Fast object allocation occurs within this space, avoiding
synchronization.
3. When TLAB is full, objects spill over to the shared heap, triggering GC
if needed.
Benefits:
Key Uses:
The Principle of Locality states that programs tend to reuse the same set of
memory locations frequently. Java optimizes cache utilization by keeping
frequently accessed data close to the CPU.
G1 GC divides the heap into regions and prioritizes collecting regions with the
most garbage, improving performance and reducing pause times.
1. Caches multiple method targets instead of looking them up every time.
2. Reduces virtual method call overhead by optimizing frequently called
methods.
3. Improves performance in polymorphic scenarios where multiple
subclasses override a method.
Impact on Performance:
Example:
while (!conditionMet) {
// Busy-wait (spinning)
}
When to Use?
Drawbacks:
jstack is a Java utility that displays the stack traces of Java threads in a
running JVM. It is useful for debugging, diagnosing deadlocks, and analyzing
performance bottlenecks.
Impact on Concurrency:
JVM flags optimize memory, garbage collection (GC), and execution speed,
directly affecting application performance.
Q130. What are Java Modules, and how do they enhance security
and maintainability?
1. Splits data into multiple sub-tasks and processes them in parallel.
2. Uses ForkJoinPool internally for task execution.
3. Ideal for large data sets where parallelism improves efficiency.
4. Order of execution is not guaranteed, unlike stream()
A deadlock occurs when two or more threads are indefinitely blocked, each
waiting for a resource held by another.
Example:
1. Definition
○ Executor: A simple interface for executing tasks asynchronously.
○ ExecutorService: A more advanced interface that extends
Executor and provides additional control over thread execution.
2. Functionality
○ Executor: Only has one method: execute(Runnable command),
which runs a task asynchronously.
○ ExecutorService: Supports more methods like submit(),
invokeAll(), shutdown(), and awaitTermination().
3. Task Handling
○ Executor: Just fires and forgets tasks without managing their
completion.
○ ExecutorService: Returns Future<T> objects, allowing task
tracking and results retrieval.
4. Shutdown Control
○ Executor: Does not provide shutdown control.
○ ExecutorService: Provides methods like shutdown(), and
shutdownNow() to gracefully stop tasks.
Null keys/values Allows one null key and Does not allow null keys or
multiple null values. values.
Key Features:
1. Purpose
○ wait(): Causes the current thread to release the lock and enter a
waiting state.
○ notify(): Wakes up one waiting thread from the waiting state.
2. Usage
○ wait(): Called when a thread needs to wait for a condition.
○ notify(): Called when a thread wants to signal a waiting thread
to resume execution.
3. Lock Requirement
○ Both wait() and notify() must be called inside a synchronized
block on the same object monitor.
4. Thread Behavior
○ wait(): The thread releases the lock and goes to the waiting
queue.
○ notify(): The awakened thread must reacquire the lock before
proceeding.
1. Purpose
○ Comparable: Used for natural ordering of objects (e.g., sorting by
ID).
○ Comparator: Used for custom ordering (e.g., sorting by name, age,
etc.).
2. Implementation
○ Comparable: Implemented by the class itself (implements
Comparable<T>).
○ Comparator: Implemented as a separate class (implements
Comparator<T>).
3. Method Used
○ Comparable: Overrides compareTo(T o).
○ Comparator: Overrides compare(T o1, T o2).
4. Usage
○ Comparable: Used when a single sorting order is needed.
○ Comparator: Used when multiple sorting criteria are required.
Transient prevents a field from being serialized, meaning it will not be saved
when an object is written to a file or transmitted over a network.
Example:
// Do something
How It Works:
Q144. How does the Unsafe class work, and what are its use cases?
Key Features:
Use Cases:
PhantomReference in Java
Key Features:
MethodHandle in Java
Key Points:
When to Use?
Retention Policy
Use Case