0% found this document useful (0 votes)
6 views3 pages

Java Core Answers

The document covers advanced Java concepts, focusing on JVM internals, memory management, garbage collection, and concurrency mechanisms. It explains key topics such as String immutability, HashMap resizing, and the differences between various locking mechanisms like ReentrantLock and synchronized. Additionally, it discusses Java's handling of exceptions, memory leaks, and efficient data processing strategies.

Uploaded by

aataarambam8
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views3 pages

Java Core Answers

The document covers advanced Java concepts, focusing on JVM internals, memory management, garbage collection, and concurrency mechanisms. It explains key topics such as String immutability, HashMap resizing, and the differences between various locking mechanisms like ReentrantLock and synchronized. Additionally, it discusses Java's handling of exceptions, memory leaks, and efficient data processing strategies.

Uploaded by

aataarambam8
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

C.

Java Core – Deep + Tricky (Q61-85)

Q61. Explain the JVM internals in detail.


JVM internals: JVM is a runtime that loads bytecode, verifies it, manages memory and threads, and
executes code via interpreter or JIT-compiled native code. Key pieces: class loaders (parent delegation),
bytecode verifier, runtime data areas (heap, stack, metaspace), garbage collector, and JIT. For interviews
highlight trade-offs: startup vs throughput, and how GC/JIT affect performance.

Q62. Draw and explain JVM memory model (stack, heap, metaspace).
JVM memory model: Heap stores objects (often generational: young/old or regions in G1), Stack holds
per-thread frames (locals & operand stack), Metaspace stores class metadata, and Native memory for JNI.
Objects reachable from roots (stacks, statics) are live. Explain how GC scans heap and stacks to find roots
and reclaim unreachable objects.

Q63. How does garbage collection really work?


Garbage collection: GC algorithms trace object graph from roots to find live objects. Common techniques:
copying (young gen), mark-and-sweep, and compaction. Modern collectors use generational hypothesis:
frequent minor GCs and occasional full/mixed GCs. Explain pauses, concurrent marking, and tuning
strategies for latency vs throughput.

Q64. Explain G1 GC vs CMS.


G1 vs CMS: CMS tried concurrent marking and sweeping to reduce pauses but suffered fragmentation
and required stop-the-world compaction. G1 divides heap into regions, prioritizes regions with most
reclaimable garbage, performs concurrent marking and incremental mixed collections, and compacts,
offering more predictable pause targets. For new apps prefer G1.

Q65. Why is String immutable? Deep internal explanation.


String immutability: Strings are immutable so they can be safely shared (interning), used as HashMap
keys, and cached (hashCode). Internally the value is a char/byte array; immutability prevents accidental
mutation and simplifies memory sharing. Use StringBuilder for heavy concatenation to avoid excess
objects.

Q66. What is String constant pool?


String constant pool: a per-JVM area where literal strings and interned strings are kept so identical literals
share one instance. Interning reduces memory but over-interning dynamic strings can harm GC. Use pool
wisely for literals and stable values.

Q67. How does HashMap resize?


HashMap resize: when size exceeds capacity*loadFactor, HashMap doubles bucket array size and
rehashes entries into new buckets. Resize is O(n) and can be costly during heavy insertions—pre-size
map if expected size is known to avoid repeated resizing.

Q68. Explain hashing + collision + chaining + treeification.


Hashing & collisions: good hashCode distributes keys; collisions occur when different keys hash to same
bucket. Java uses chaining (linked lists) and converts long chains to balanced trees (treeification) in Java
8+ to keep lookup O(log n) in worst cases. Ensure stable, well-distributed hashCode implementations.

Q69. What is ConcurrentHashMap’s segmentation principle?


ConcurrentHashMap segmentation principle: older CHM used segments (locks per segment). Java 8
replaced segments with per-bin CAS and synchronized on bin nodes, enabling finer-grained locking and
lock-free reads. This reduces contention and improves throughput for concurrent access.

Q70. What is volatile and how does it affect memory ordering?


volatile: volatile ensures visibility and prevents certain re-orderings: a write to volatile happens-before
subsequent reads. It is suitable for flags and state visibility but does not make compound operations
atomic. Use Atomic classes for atomic updates.

Q71. Difference between synchronized block and synchronized method internally.


synchronized block vs method: both use object monitors. synchronized method implicitly locks 'this' (or
class for static), while synchronized(block) locks a specified object, allowing narrower critical sections.
JVM uses monitorenter/monitorexit bytecodes and optimizations like biased locking to reduce overhead.

Q72. Explain ReentrantLock vs synchronized.


ReentrantLock vs synchronized: ReentrantLock offers features like tryLock, timed locks, and Condition
support, implemented with AQS queues. synchronized is simpler, managed by JVM, and may have lower
footprint for simple use. Choose ReentrantLock for advanced control.

Q73. What is thread starvation and how to prevent it?


Thread starvation: occurs when some threads never get CPU/time or locks due to unfair scheduling.
Prevent with fair locks, proper thread priorities, avoid long-running hold of locks, and design thread pools
with appropriate queue policies to avoid starving workers.

Q74. How does Java handle deadlocks?


Deadlocks: JVM won't resolve deadlocks automatically; detect using tools (jstack, thread dumps) and fix
by enforcing lock ordering, using timeouts (tryLock), reducing lock scope, or redesigning to avoid lock
cycles.

Q75. How does the JVM handle exceptions internally?


JVM exceptions: throwing creates Throwable, optionally fills stack trace (costly), and JVM unwinds frames
to find a matching handler using exception tables generated at compile time. Use exceptions for
exceptional conditions and avoid frequent throw-catch in hot paths.

Q76. Explain class loading process step-by-step.


Class loading: Loading (find and read class bytes), Linking (verification, preparation — allocate static
fields), Initialization (execute static initializers). Parent delegation prevents multiple copies of core classes;
custom classloaders enable isolation and hot reload patterns.

Q77. What is the difference between JIT and interpreter?


JIT vs interpreter: Interpreter executes bytecode directly (fast startup), JIT compiles frequently used
methods into native machine code for speed at the cost of compilation time and memory. JIT uses profiling
to apply aggressive optimizations to hot paths.

Q78. How does Stream API use lazy evaluation?


Stream API lazy evaluation: intermediate operations build an internal pipeline but do not process elements
until a terminal operation triggers evaluation. This enables optimizations and short-circuiting. Keep
pipelines side-effect free for predictability.
Q79. Internal working of Optional.
Optional internals: Optional wraps a nullable value to avoid null checks; it stores a single reference and
offers map/flatMap/filter to chain operations. Use Optional in API responses but avoid as fields in entities
to reduce overhead.

Q80. What causes memory leaks in Java?


Memory leaks in Java: caused by unintended strong references (static caches, listeners, threadlocals,
long-lived collections). Diagnose with heap dumps and MAT; fix by clearing references, using weak/soft
refs for caches, and lifecycle-aware resource management.

Q81. How do you handle large data processing in Java efficiently?


Large data processing: stream or batch process in chunks, use streaming parsers (Jackson streaming),
avoid loading entire dataset into memory, use memory-mapped files or external stores, and consider
distributed frameworks (Spark) when scale exceeds single-node capacity.

Q82. What is the difference between fail-fast and fail-safe iterators?


Fail-fast vs fail-safe iterators: fail-fast iterate over collection and detect structural modification, throwing
ConcurrentModificationException. Fail-safe (CopyOnWriteArrayList, ConcurrentHashMap) work on
snapshots or concurrent structures and won't throw, but may not reflect latest changes.

Q83. How does ForkJoinPool work?


ForkJoinPool: uses divide-and-conquer tasks and work-stealing: tasks split into subtasks, workers keep
deques and idle workers steal from others, giving excellent CPU utilization for parallel algorithms. Best for
many small, compute-bound subtasks.

Q84. What are CompletableFutures?


CompletableFutures: an API for composing asynchronous computations, allowing callbacks, chaining,
combining multiple futures, and non-blocking composition. Useful for parallel remote calls and building
reactive-style flows without blocking threads.

Q85. Explain functional interfaces and lambda internals.


Functional interfaces & lambdas: a functional interface has one abstract method; lambdas are
implemented via invokedynamic and method handles, enabling lightweight runtime creation. Lambdas
capture effectively-final variables and produce concise, testable code.

You might also like