Beginner Level (0–1 Years)
1. What happens when you try to override a static method in Java?
Answer:
Static methods belong to the class, not the instance, so they cannot be overridden; they can only be hidden. Hiding means the method called depends on the reference type, not the object type. This is not true overriding, which applies to instance methods.
class A {
static void display() {
System.out.println("A");
}
}
class B extends A {
static void display() {
System.out.println("B");
}
}
A obj = new B();
obj.display(); // Outputs "A"
2. Can a Java interface contain static methods, and can they be inherited?
Answer:
Since Java 8, interfaces can have static methods, but they are not inherited by implementing classes. They must be called using the interface name.
interface MyInterface {
static void greet() {
System.out.println("Hello");
}
}
class MyClass implements MyInterface {}
MyInterface.greet(); // Correct
// MyClass.greet(); // Compilation error
3. What is the default value of a local variable in Java?
Answer:
Local variables in Java do not have a default value and must be initialized before use, or the code will not compile.
void method() {
int x;
System.out.println(x); // Compilation error: x not initialized
}
4. What is the output of comparing two wrapper objects using “==”?
Answer:
Using “==” with wrapper objects compares references, not values. For integers between -128 and 127, Java caches values, so “==” may return true. Use equals()
for value comparison.
Integer a = 100;
Integer b = 100;
System.out.println(a == b); // true
Integer c = 200;
Integer d = 200;
System.out.println(c == d); // false
5. Can a Java class be both abstract and final?
Answer:
No. An abstract class must be extended, while a final class cannot be extended. These modifiers are mutually exclusive.
6. What is the result of dividing an integer by zero in Java?
Answer:
Dividing an integer by zero throws an ArithmeticException
. Dividing a floating-point number by zero results in positive or negative Infinity
, depending on the sign.
int x = 5 / 0; // Throws ArithmeticException
double y = 5.0 / 0; // Positive Infinity
double z = -5.0 / 0; // Negative Infinity
7. Can a constructor be marked static in Java?
Answer:
No. Constructors initialize instances, which are non-static. Declaring a constructor static causes a compilation error.
8. How does Java handle object equality with equals()
and ==
?
Answer:
==
compares object references; equals()
compares values if overridden. The default equals()
in Object
behaves like ==
.
String a = new String("hi");
String b = new String("hi");
System.out.println(a == b); // false
System.out.println(a.equals(b)); // true
9. What happens if you call this()
and super()
in the same constructor?
Answer:
Only one constructor call (this()
or super()
) is allowed as the first statement in a constructor. Calling both results in a compilation error.
10. What is the output of a loop where the condition is never true?
Answer:
The loop body will not execute if the condition is false at initialization, such as in for(int i = 0; i < 0; i++)
.
11. Is it possible to overload a method by changing only the return type?
Answer:
No. Method overloading requires a different parameter list. Changing only the return type is not sufficient.
12. What happens when you create an array with a negative size?
Answer:
Code like int[] arr = new int[-5];
compiles but throws a NegativeArraySizeException
at runtime.
13. Can the main
method be overloaded?
Answer:
Yes, the main
method can be overloaded, but only the public static void main(String[] args)
signature serves as the program entry point.
14. Does Java support multiple inheritance?
Answer:
Java does not support multiple inheritance with classes to avoid the diamond problem but supports it through interfaces.
15. What is the result of comparing a String with null using equals()
?
Answer:
"abc".equals(null)
returns false
. Calling null.equals("abc")
throws a NullPointerException
.
16. Can a class implement two interfaces with the same method signature?
Answer:
Yes, a class can implement multiple interfaces with the same method signature, providing a single implementation.
17. Can a Java source file contain multiple public classes?
Answer:
No, a Java source file can contain only one public class, which must match the file name, but can include multiple non-public classes.
18. Can an abstract class have a constructor?
Answer:
Yes, abstract classes can have constructors, which are called during subclass instantiation.
abstract class A {
A() { System.out.println("A's constructor"); }
}
class B extends A {}
B b = new B(); // Outputs "A's constructor"
19. Is String
thread-safe in Java?
Answer:
Yes, String
objects are thread-safe because they are immutable, preventing concurrent modification.
20. Will this compile: final int x; x = 10;
?
Answer:
Yes, a final
variable can be assigned once before use, such as in a constructor or directly.
class Test {
final int x;
Test() { x = 10; }
}
21. What is the purpose of a try-catch
block in Java?
Answer:
A try-catch
block handles exceptions to prevent program crashes. Code that might throw an exception goes in try
, and catch
handles it.
try {
int x = 5 / 0;
} catch (ArithmeticException e) {
System.out.println("Cannot divide by zero");
}
22. Why is the String class immutable in Java?
Answer:
Strings are immutable for security, thread-safety, and memory efficiency (via the String pool). Operations create new Strings rather than modifying existing ones.
String s = "Hello";
s = s.concat(" World"); // Creates new String
23. What are the access modifiers in Java, and what do they mean?
Answer:
Java has four access modifiers: public
(accessible everywhere), protected
(accessible within package and subclasses), default
(package-private, accessible within package), and private
(accessible only within the class).
24. How do you create and use an ArrayList in Java?
Answer:
ArrayList
is a resizable array in the Collections Framework, allowing dynamic addition, removal, and access of elements.
import java.util.ArrayList;
ArrayList list = new ArrayList<>();
list.add("Apple");
list.remove(0);
25. What are the rules for overriding a method in Java?
Answer:
The overriding method must have the same name, parameters, and return type (or covariant). It cannot throw broader checked exceptions or have a more restrictive access modifier.
class A {
void display() { System.out.println("A"); }
}
class B extends A {
@Override
void display() { System.out.println("B"); }
}
👋 Need top Java developers for your project? Interview this week!
Fill out the form to book a call with our team. We’ll match you to the top developers who meet your requirements, and you’ll be interviewing this week!
Intermediate Level (1–3 Years)
1. What is the difference between a shallow copy and a deep copy in Java?
Answer:
A shallow copy copies field values, including references to objects, which point to the same memory. A deep copy creates new instances of nested objects, ensuring full independence.
class Address implements Cloneable {
String city;
Address(String city) { this.city = city; }
protected Object clone() throws CloneNotSupportedException {
return super.clone();
}
}
class Person implements Cloneable {
Address address;
Person(Address address) { this.address = address; }
// Shallow copy
protected Object clone() throws CloneNotSupportedException {
return super.clone();
}
// Deep copy
public Person deepCopy() throws CloneNotSupportedException {
Person p = (Person) super.clone();
p.address = (Address) address.clone();
return p;
}
}
2. How does Java achieve memory management and garbage collection?
Answer:
Java uses automatic garbage collection to track object references. When no references remain, objects are marked for collection. Algorithms include generational GC and G1 GC.
3. How does the Java Streams API process data?
Answer:
The Streams API processes collections functionally, supporting operations like filter, map, and reduce. Streams are lazy and can be parallelized.
List numbers = Arrays.asList(1, 2, 3, 4);
numbers.stream().filter(n -> n % 2 == 0).forEach(System.out::println); // Prints 2, 4
4. What is the difference between HashMap
and ConcurrentHashMap
?
Answer:
HashMap
is not thread-safe and may cause race conditions. ConcurrentHashMap
supports concurrent access using bucket-level locking for better performance in multi-threaded environments.
5. What are covariant return types in Java?
Answer:
Covariant return types allow an overridden method to return a subtype of the original method’s return type.
class Animal {}
class Dog extends Animal {}
class A {
Animal getAnimal() { return new Animal(); }
}
class B extends A {
@Override
Dog getAnimal() { return new Dog(); }
}
6. What happens if you put a key with hashCode()
always returning the same value into a HashMap
?
Answer:
All keys land in the same bucket, forming a linked list or tree (Java 8+), degrading performance from O(1) to O(n) or O(log n) for get/put operations.
7. Can two threads call two synchronized methods of the same object simultaneously?
Answer:
No, if the methods are synchronized on the same object instance. Only one thread can hold the lock at a time.
8. What is the use of the volatile
keyword in Java?
Answer:
volatile
ensures visibility of variable changes across threads, preventing caching in thread-local memory.
volatile boolean flag = false;
// Thread 1
flag = true;
// Thread 2
if (flag) { System.out.println("Flag is true"); }
9. How does Java handle integer overflow?
Answer:
Java does not throw an exception on integer overflow; it wraps around using two’s complement representation.
int max = Integer.MAX_VALUE;
System.out.println(max + 1); // Prints Integer.MIN_VALUE
10. What is the difference between StringBuilder
and StringBuffer
?
Answer:
StringBuilder
is not thread-safe but faster, while StringBuffer
is synchronized and thread-safe, making it slower.
11. How does Java handle method overloading and resolution at compile time?
Answer:
Java uses static binding for overloaded methods, choosing the method based on reference type and argument types at compile time.
void print(Object o) { System.out.println("Object"); }
void print(String s) { System.out.println("String"); }
print(null); // Prints "String" (most specific match)
12. What is the purpose of Optional
in Java 8?
Answer:
Optional
is a container to avoid NullPointerException
, indicating a value may or may not be present.
Optional name = Optional.ofNullable(getName());
name.ifPresent(System.out::println);
13. Can a functional interface have default methods?
Answer:
Yes, a functional interface can have multiple default or static methods but only one abstract method.
14. What is a memory leak in Java, and how can it occur despite garbage collection?
Answer:
Memory leaks occur when unused objects are still referenced, preventing GC. Causes include static collections, listeners, or caches retaining references.
15. How does Java handle exception chaining?
Answer:
Java supports exception chaining via Throwable
constructors that accept a cause, allowing wrapping of lower-level exceptions.
throw new IOException("Wrapper", new SQLException("Cause"));
16. What is the benefit of using a thread pool with ExecutorService
?
Answer:
Thread pools reuse threads, reducing creation overhead. ExecutorService
manages tasks, supports shutdown, and handles thread lifecycle.
ExecutorService executor = Executors.newFixedThreadPool(2);
executor.submit(() -> System.out.println("Task"));
executor.shutdown();
17. What does it mean when a method is synchronized in Java?
Answer:
A synchronized method ensures only one thread can execute it at a time for a given object or class, preventing race conditions by locking the monitor.
18. How does Java implement polymorphism?
Answer:
Java uses dynamic method dispatch for runtime polymorphism, resolving method calls based on the actual object’s type.
19. What is the output of modifying a collection while iterating over it using a for-each loop?
Answer:
It throws a ConcurrentModificationException
unless using an iterator’s remove method or concurrent collections.
20. How is the equals()
method related to hashCode()
?
Answer:
If two objects are equal via equals()
, they must have the same hashCode()
, critical for hash-based collections like HashMap
.
21. Can you override a private or static method in Java?
Answer:
No. Private methods are not visible to subclasses, and static methods can be hidden but not overridden.
22. What is the difference between fail-fast and fail-safe iterators?
Answer:
Fail-fast iterators throw ConcurrentModificationException
if the collection is modified during iteration. Fail-safe iterators work on a copy, avoiding exceptions.
Iterator it = list.iterator();
list.add("new"); // Fail-fast: throws exception
23. What is the effect of making a field static
in a Java class?
Answer:
Static fields are shared across all instances, belonging to the class itself, not individual objects.
24. What is the difference between checked and unchecked exceptions?
Answer:
Checked exceptions must be declared or handled with try-catch. Unchecked exceptions (subclasses of RuntimeException
) are optional to catch and indicate programming errors.
25. How does the finally
block behave if System.exit()
is called in try
?
Answer:
The finally
block will not execute if System.exit()
is called, as the JVM terminates. Registered shutdown hooks may still run.
26. What is method reference in Java 8 and how is it different from a lambda?
Answer:
Method references are shorthand for lambdas that call a method, improving readability.
list.forEach(System.out::println); // Instead of x -> System.out.println(x)
27. Can a constructor be synchronized in Java?
Answer:
No, constructors cannot be synchronized, but code inside them can be synchronized if needed.
28. How does autoboxing/unboxing work in Java?
Answer:
Autoboxing converts primitives to wrapper classes, and unboxing does the reverse. Java inserts the conversion code at compile time.
Integer x = 10; // Autoboxing
int y = x; // Unboxing
29. What are default and static methods in interfaces used for?
Answer:
Default methods provide base implementations for backward compatibility. Static methods offer utility functions specific to the interface.
30. How does final
keyword behave with reference variables?
Answer:
final
reference variables cannot be reassigned, but the object they point to can be modified if mutable.
final List list = new ArrayList<>();
list.add("item"); // OK
list = new ArrayList<>(); // Compilation error
31. What is the difference between TreeSet
and HashSet
?
Answer:
HashSet
uses a hash table with no ordering. TreeSet
uses a red-black tree, keeping elements sorted by natural order or a comparator.
32. Can a thread acquire multiple locks in Java?
Answer:
Yes, a thread can acquire multiple locks, but this risks deadlocks if locks are not acquired consistently.
33. What does super
refer to in Java?
Answer:
super
refers to the immediate parent class, used to access overridden methods or parent constructors.
34. Why is String immutable in Java?
Answer:
Immutability ensures thread safety, caching, and security, improving performance and reliability in the JVM.
35. What is the difference between Comparable
and Comparator
?
Answer:
Comparable
defines natural order via compareTo()
. Comparator
is a separate object for custom orderings via compare()
.
36. What are annotations in Java, and how are they used?
Answer:
Annotations provide metadata for code, used by compilers or frameworks. Examples include @Override
, @Deprecated
, or custom annotations in Spring.
@Override
public String toString() { return "Example"; }
37. What is type erasure in Java generics?
Answer:
Type erasure removes generic type information at runtime, replacing it with raw types for backward compatibility.
38. Why should equals()
be overridden with hashCode()
?
Answer:
Hash-based collections use both methods. If equals()
is overridden, hashCode()
must be consistent to ensure correct behavior.
39. What is the difference between ==
and equals()
when comparing Strings?
Answer:
==
compares references; equals()
compares values. Different String objects with the same content are equals()
true but ==
false unless interned.
40. What are some common thread-safe collections in Java?
Answer:
Examples include ConcurrentHashMap
, CopyOnWriteArrayList
, BlockingQueue
, and Collections.synchronizedList()
.
41. What happens when you throw an exception in a static block?
Answer:
An uncaught exception in a static block causes the class to fail loading, throwing an ExceptionInInitializerError
.
42. What is the difference between weak and soft references in Java?
Answer:
Weak references (WeakReference
) are eligible for GC when no strong references exist. Soft references (SoftReference
) are retained longer, useful for caches, until memory is needed.
WeakReference weak = new WeakReference<>(new String("Weak"));
43. How can you make an object immutable in Java?
Answer:
Make the class final
, fields private final
, and avoid setters. Return defensive copies for mutable fields.
44. What is the significance of the transient
keyword in Java serialization?
Answer:
transient
fields are excluded from serialization, useful for sensitive data or non-serializable fields.
private transient String password;
45. What is the difference between Executor
and ExecutorService
?
Answer:
Executor
is a simple interface for running tasks. ExecutorService
extends it, providing thread pool management and shutdown capabilities.
46. What are lambda expressions in Java and where are they typically used?
Answer:
Lambda expressions implement functional interfaces concisely, used in collections, streams, and event handling.
list.forEach(e -> System.out.println(e));
47. Can you synchronize a static method? If so, what does it lock on?
Answer:
Yes, a static synchronized method locks on the Class
object, not an instance.
48. How does try-with-resources simplify resource management?
Answer:
Try-with-resources automatically closes resources implementing AutoCloseable
, ensuring cleanup even if exceptions occur.
try (FileReader fr = new FileReader("file.txt")) {
// Use file
} catch (IOException e) {
// Handle exception
}
49. What are bounded type parameters in Java generics?
Answer:
Bounded types restrict generics to a range using <T extends Class>
, allowing access to methods of the bound class/interface.
public void print(T t) {
System.out.println(t.doubleValue());
}
50. What is the role of JDBC in Java applications?
Answer:
JDBC (Java Database Connectivity) enables Java applications to interact with databases using SQL, providing APIs for connections, statements, and result sets.
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/db", "user", "pass");
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM users");

Hire Top LATAM Developers: Guide
We’ve prepared this guide that covers benefits, costs, recruitment, and remote team management to a succesful hiring of developers in LATAM.
Fill out the form to get our guide.
Advanced Level (3+ Years)
1. What are the differences between ReentrantLock
and synchronized
in Java?
Answer:
ReentrantLock
offers flexibility like try-lock, timeouts, and interruptible locks, while synchronized
is simpler, implicitly managing monitor acquisition/release.
ReentrantLock lock = new ReentrantLock();
lock.lock();
try {
// critical section
} finally {
lock.unlock();
}
// Synchronized equivalent
synchronized (obj) {
// critical section
}
2. How does Java’s memory model handle the visibility of shared variables between threads?
Answer:
The Java Memory Model (JMM) ensures visibility using volatile
, synchronized blocks, and final fields. Without synchronization, thread-local caching may cause stale reads.
volatile int counter = 0;
// Thread 1
counter++;
// Thread 2 sees updated value
System.out.println(counter);
3. What is the difference between CompletableFuture
and Future
in Java?
Answer:
CompletableFuture
supports chaining, async computation, exception handling, and combining results. Future
only provides blocking get without reactive capabilities.
4. Explain the difference between a deep copy and serialization.
Answer:
A deep copy creates a new instance with recursively duplicated objects. Serialization converts objects to a byte stream for persistence or transport, recreating state later.
5. What is false sharing in concurrent programming?
Answer:
False sharing occurs when threads access different variables in the same cache line, causing cache invalidation and performance degradation. Padding or @Contended
mitigates this.
6. How does the ForkJoinPool
work in Java?
Answer:
ForkJoinPool
uses work-stealing, where idle threads steal tasks from others. It’s efficient for divide-and-conquer tasks like RecursiveTask
or RecursiveAction
.
7. What is a ClassLoader leak and how can it be detected?
Answer:
ClassLoader leaks occur when classes or static references prevent garbage collection, common in application servers. Detect using VisualVM or heap dumps.
8. What are soft, weak, and phantom references in Java?
Answer:
- Soft: Collected when memory is low (e.g., caches).
- Weak: Collected eagerly when not strongly referenced.
- Phantom: Collected after finalization for cleanup tracking.
WeakReference weak = new WeakReference<>(new String("Weak"));
9. Why is Enum
considered a good candidate for Singleton?
Answer:
Enum
ensures a single instance, serialization safety, and protection against reflection attacks.
public enum Singleton {
INSTANCE;
}
10. What are the consequences of overriding equals()
but not hashCode()
?
Answer:
Violates the contract where equal objects must have equal hash codes, causing inconsistent behavior in hash-based collections like HashMap
or HashSet
.
11. What is the role of the Unsafe
class in Java?
Answer:
sun.misc.Unsafe
provides low-level operations like direct memory access, CAS, and thread control. Used in high-performance libraries but unsafe and non-portable.
12. How can you tune the JVM’s garbage collector for high-performance applications?
Answer:
Tuning involves selecting GC algorithms (e.g., G1, ZGC), adjusting heap sizes (`-Xms`, `-Xmx`), and setting parameters like `-XX:+UseG1GC` or `-XX:MaxGCPauseMillis`. Analyze GC logs for bottlenecks.
// JVM options: -Xms2g -Xmx4g -XX:+UseG1GC -XX:MaxGCPauseMillis=100
13. What is the difference between WeakHashMap
and HashMap
?
Answer:
WeakHashMap
uses weak references for keys, allowing GC when no strong references remain. HashMap
holds strong references, retaining keys/values until removed.
14. What is a memory barrier and how does Java enforce it?
Answer:
A memory barrier prevents reordering of reads/writes. Java enforces barriers using volatile
, synchronized blocks, and atomic classes, relying on CPU instructions.
15. What are some common causes of OutOfMemoryError
in Java?
Answer:
Causes include memory leaks, large object allocation, improper caching, thread leakage, and excessive use of finalizers or class loaders.
16. Explain biased locking and how it improves performance.
Answer:
Biased locking allows a thread to acquire a lock without atomic instructions if uncontended. It’s revoked if contention occurs, reducing synchronization overhead.
17. How do you prevent deadlock in a multi-threaded Java application?
Answer:
Prevent deadlock by acquiring locks in a consistent order, using timeouts, avoiding nested locks, or employing try-locks like ReentrantLock.tryLock()
.
18. What is tail-call optimization and does Java support it?
Answer:
Tail-call optimization reuses stack frames for recursive calls. Java doesn’t support it natively due to stack trace preservation and JVM complexity, risking StackOverflowError
.
19. What is the impact of using too many threads?
Answer:
Excessive threads cause CPU contention, context switching, memory exhaustion, and reduced performance. Thread pools or reactive models improve scalability.
20. How do TreeMap
and HashMap
differ in implementation and use cases?
Answer:
TreeMap
uses a Red-Black tree for sorted order with log(n) operations. HashMap
uses hashing for average O(1) operations. Use TreeMap
for sorted access.
21. How does ThreadLocal
work, and what are its use cases?
Answer:
ThreadLocal
provides thread-confined variables, each thread having its own copy. Useful for user sessions, database connections, or SimpleDateFormat
.
ThreadLocal formatter = ThreadLocal.withInitial(() -> new SimpleDateFormat("yyyy-MM-dd"));
22. How is the intern()
method used in the String
class?
Answer:
intern()
returns a string from the string pool, adding it if absent, reducing memory usage for repeated strings.
23. What is the significance of java.lang.instrument
package?
Answer:
It enables Java agents to modify bytecode at runtime or class loading, used for profiling, monitoring, or altering class behavior.
24. How does Java support reactive programming?
Answer:
Java supports reactive programming via libraries like Project Reactor and RxJava, and the Flow
API (Java 9) based on Reactive Streams.
25. What is method handle in Java and how is it different from reflection?
Answer:
MethodHandle
is a faster, type-safe alternative to reflection for dynamic method invocation, used in dynamic languages on the JVM.
MethodHandles.Lookup lookup = MethodHandles.lookup();
MethodHandle mh = lookup.findVirtual(String.class, "length", MethodType.methodType(int.class));
26. What are the limitations of Java’s type erasure in generics?
Answer:
Type erasure removes generic type info at runtime, preventing type checks or instantiation. It disallows overloading based solely on generic types.
27. What is the difference between readResolve()
and writeReplace()
?
Answer:
writeReplace()
nominates a replacement during serialization; readResolve()
substitutes after deserialization, ensuring singleton or proxy behavior.
28. How do you prevent subclassing in Java?
Answer:
Use final
, private constructors with static factory methods, or sealed classes (Java 17+) to restrict subclassing.
29. How do you create an immutable collection in Java?
Answer:
Use Collections.unmodifiable*
or factory methods like List.of()
, Set.of()
, Map.of()
(Java 9+).
List list = List.of("A", "B", "C");
30. What is the purpose of sun.misc.Cleaner
or java.lang.ref.Cleaner
?
Answer:
They register cleanup actions for objects after they become unreachable, more reliable than finalizers, not tied to GC timing.
31. What are Sealed Classes in Java and what problem do they solve?
Answer:
Sealed classes (Java 17) restrict which classes can extend or implement them, improving type hierarchy control and supporting pattern matching.
public sealed class Shape permits Circle, Rectangle {}
final class Circle extends Shape {}
final class Rectangle extends Shape {}
32. How does VarHandle
differ from Atomic*
classes?
Answer:
VarHandle
provides a flexible, low-level API for atomic and volatile access to variables, unlike Atomic*
classes, which are specialized.
33. What is the difference between ==
, equals()
, and Objects.equals()
?
Answer:
==
: Compares references.equals()
: Compares content, overridable.Objects.equals()
: Null-safeequals()
.
34. What is escape analysis and how does it benefit performance?
Answer:
Escape analysis allows stack allocation of objects, reducing GC pressure and improving performance by avoiding heap allocation.
35. How can you inspect or modify bytecode in Java?
Answer:
Use libraries like ASM, BCEL, or Javassist to programmatically read and manipulate bytecode at load time or post-compilation.
36. What is the use of StampedLock
in Java?
Answer:
StampedLock
offers read/write/optimistic locking, providing higher concurrency than ReentrantReadWriteLock
for read-heavy scenarios.
37. What are records in Java and what problems do they solve?
Answer:
Records (Java 14-16) are immutable data carriers, reducing boilerplate for POJOs by auto-generating constructors, accessors, equals()
, hashCode()
, and toString()
.
public record Point(int x, int y) {}
38. How can you handle backpressure in reactive streams?
Answer:
Backpressure is managed via the Publisher
–Subscriber
protocol, where subscribers request items. Libraries like Project Reactor offer built-in strategies.
39. How can you ensure consistent hash codes across JVM instances?
Answer:
Use deterministic hashing (e.g., based on UUIDs or stable fields) instead of default Object.hashCode()
, which varies across executions.
40. What are the implications of memory-mapped files in Java?
Answer:
Memory-mapped files (via FileChannel.map()
) enable high-performance I/O by mapping file regions to memory. Unmapping is required to avoid resource leaks.
41. What is the difference between flatMap()
and map()
in streams?
Answer:
map()
transforms elements one-to-one; flatMap()
flattens nested structures like Stream<Stream>
into Stream
.
list.stream().flatMap(List::stream)
42. How can you make a classloader hierarchy leak-proof in long-running applications?
Answer:
Avoid static references to child classloader-loaded classes, unregister listeners/threads, and avoid global singleton caching to allow garbage collection.
43. How does the Java runtime prevent method inlining from breaking debugging?
Answer:
The JVM avoids inlining during debugging and can deoptimize methods if breakpoints or stepping are enabled.
44. How does the JVM decide when to trigger Just-In-Time (JIT) compilation?
Answer:
JIT compilation triggers for “hot” methods based on execution counters, compiling to native code for performance, with potential re-optimization.
45. What are the risks of using finalize()
, and what should be used instead?
Answer:
finalize()
is unreliable and deprecated, causing performance issues. Use Cleaner
for non-resource cleanup or AutoCloseable
with try-with-resources for resources.
46. What is the Java Module System, and how does it improve application design?
Answer:
Introduced in Java 9, JPMS defines module boundaries, dependencies, and exports via module-info.java
, enhancing encapsulation, security, and maintainability.
module com.example {
exports com.example.api;
requires java.base;
}
47. How can you use Java annotations to generate code at compile time?
Answer:
Annotation Processors (JSR 269) scan annotations and generate files using Filer
. Tools like Lombok and Dagger reduce boilerplate this way.
48. How does the ConcurrentHashMap
handle concurrent modifications?
Answer:
It uses lock striping and CAS operations for high concurrency, locking buckets independently and using Unsafe
for atomic updates.
49. What are virtual threads in Java, and how do they differ from platform threads?
“ System:Answer:
Virtual threads (Java 21+) are lightweight, JVM-managed threads, not tied to OS threads, enabling millions of threads with low overhead. Platform threads map directly to OS threads, limiting scalability.
try (var executor = Executors.newVirtualThreadPerTaskExecutor()) {
executor.submit(() -> System.out.println("Running in virtual thread"));
}
50. How does pattern matching enhance Java’s type safety and code readability?
Answer:
Pattern matching (Java 17+) simplifies type checking and casting with instanceof
and switch expressions, reducing boilerplate and errors.
Object obj = "Hello";
if (obj instanceof String s) {
System.out.println(s.toUpperCase());
}