Java Interview QnA (Part-1)
Here is the list of 10 questions that you must know if going for Java Interview.
1. How does Java manage memory in the heap and stack?
- Heap: Used for storing objects and class-level variables. Managed by garbage collection.
- Stack: Stores method calls, local variables, and function call traces. Operates on a Last In First Out (LIFO) basis.
Key Points:
- The stack is thread-specific, while the heap is shared among all threads.
- Garbage collection reclaims heap memory, but stack memory is reclaimed when the method call ends.
public class MemoryExample {
static int staticVar = 10; // Stored in Method Area
int instanceVar; // Stored in Heap
public void methodExample() {
int localVar = 5; // Stored in Stack
}
}
**Note — if you love to watch video — check here
2. What is the difference between deep copy and shallow copy in Java?
- Shallow Copy: Copies only the object’s references. Changes to referenced objects affect the copy.
- Deep Copy: Creates a completely independent copy, including copies of objects within.
class ShallowCopyExample implements Cloneable {
int[] data = {1, 2, 3};
@Override
protected Object clone() throws CloneNotSupportedException {
return super.clone(); // Shallow copy
}
}
To implement deep copy, manually copy referenced objects:
ShallowCopyExample deepClone = new ShallowCopyExample();
deepClone.data = Arrays.copyOf(original.data, original.data.length);
3. Explain volatile
keyword and how it resolves visibility issues.
- Marks a variable as directly readable/writable from main memory, bypassing thread-local cache.
- Ensures visibility of changes across threads but doesn’t guarantee atomicity.
class VolatileExample {
private volatile boolean flag = true;
public void runThread() {
while (flag) {
// Do something
}
}
public void stopThread() {
flag = false; // Immediately visible to all threads
}
}
4. How does Java’s ConcurrentHashMap
ensure thread safety?
- Uses bucket-level locking (segment locking) to reduce contention.
- From Java 8, it uses a CAS (Compare-And-Swap) mechanism for updates.
- It doesn’t block the entire map during operations, ensuring better performance compared to
Hashtable
.
ConcurrentHashMap<String, Integer> map = new ConcurrentHashMap<>();
map.put("key", 1); // Thread-safe operation
5. Explain the CompletableFuture
API and its advantages.
Introduced in Java 8, it allows non-blocking, asynchronous programming.
- Advantages: Avoids thread blocking, supports functional programming, and allows composing multiple tasks.
CompletableFuture.supplyAsync(() -> "Task")
.thenApply(result -> result + " Completed")
.thenAccept(System.out::println);
6. How does Java achieve immutability in String
class?
- Internally final: Uses a final array to store characters.
- Any modification creates a new string, leaving the original unchanged.
- Security and caching: Used in sensitive areas like class loading and caching mechanisms.
String s1 = "Java";
String s2 = s1.concat(" Programming");
System.out.println(s1); // Output: "Java"
7. How do you avoid deadlocks in a multithreading environment?
- Avoid Nested Locks: Always acquire locks in a consistent order.
- Use
tryLock()
: Prevent threads from waiting indefinitely. - Lock Timeout: Use timeouts to exit deadlock-prone situations.
Lock lock1 = new ReentrantLock();
Lock lock2 = new ReentrantLock();
boolean acquiredLock1 = lock1.tryLock(10, TimeUnit.MILLISECONDS);
boolean acquiredLock2 = lock2.tryLock(10, TimeUnit.MILLISECONDS);
8. What are the different types of class loaders in Java?
- Bootstrap ClassLoader: Loads core Java classes (e.g.,
java.lang.*
). - Extension ClassLoader: Loads classes from the
ext
directory. - Application ClassLoader: Loads classes from the application’s classpath.
ClassLoader classLoader = MyClass.class.getClassLoader();
System.out.println(classLoader.getClass().getName());
9. What is the difference between Callable
and Runnable
?
- Runnable: Does not return a result or throw checked exceptions.
- Callable: Returns a result and can throw checked exceptions.
Callable<Integer> callable = () -> 42;
ExecutorService executor = Executors.newSingleThreadExecutor();
Future<Integer> future = executor.submit(callable);
System.out.println(future.get());
10. What is Optional
in Java, and why is it useful?
Introduced in Java 8 to handle null values gracefully, avoiding NullPointerException
.
Optional<String> optional = Optional.ofNullable(null);
optional.ifPresent(System.out::println); // Won’t execute
String result = optional.orElse("Default Value"); // Returns "Default Value"
— — — — -
Let me know your thoughts/feedback in the comment section. Clap this story if found useful and follow me for more such content.
If you want to deep dive to any of the question above let me know in the comment, i can plan to create the dedicated video for that too.