Java Coder

Java Coder Welcome! Be here to learn & prepare java interviews.

04/07/2025

What are memory leaks and how can they be avoided?

A memory leak in Java occurs when objects are no longer used but still referenced, preventing GC from reclaiming memory.

Common causes:
• Static collections (e.g., List, Map) holding unused objects
• Listeners or callbacks not deregistered
• Long-lived references to temporary objects

Avoidance tips:
• Nullify references when done
• Use WeakReference for cache-like structures
• Use profiling tools (e.g., VisualVM, JProfiler)

04/07/2025

What is the Java memory model?

The Java Memory Model (JMM) defines how variables are read and written in multithreaded environments.
It ensures:
• Visibility: When one thread updates a variable, others can see the change.
• Atomicity: Some operations (e.g., reading/writing int) are atomic by default.
• Ordering: Prevents reordering of instructions that could cause bugs in multithreading.

Java divides memory into:
• Heap: Objects and class instances.
• Stack: Method calls and local variables.
• Method Area: Class metadata.
• Program Counter Register: Current thread ex*****on point.
• Native Method Stack: For native (non-Java) methods.

What is method overloading and method overriding?⸻🔧 Examples👉 Method Overloading:public class Calculator {    public int...
08/06/2025

What is method overloading and method overriding?



🔧 Examples

👉 Method Overloading:

public class Calculator {
public int add(int a, int b) {
return a + b;
}

public double add(double a, double b) {
return a + b;
}

public int add(int a, int b, int c) {
return a + b + c;
}
}

👉 Method Overriding:

class Animal {
public void makeSound() {
System.out.println("Animal makes a sound");
}
}

class Dog extends Animal {

public void makeSound() {
System.out.println("Dog barks");
}
}

21/05/2025

What are volatile, wait(), notify(), and notifyAll()?

✅ volatile Keyword

Definition:
• volatile is a modifier used for variables that may be accessed by multiple threads.

Purpose:
• It tells the JVM not to cache the value of this variable and always read from the main memory.
• It ensures visibility, but not atomicity.

private volatile boolean flag = false;

This ensures that when one thread updates flag, other threads immediately see the updated value.

Use Case:

Used for flags or state variables shared across threads (e.g., stopping a thread).

✅ wait()

Definition:
• Causes the current thread to wait until another thread calls notify() or notifyAll() on the same object.

Key Points:
• Must be called from a synchronized block or method.
• It releases the monitor (lock) on the object, allowing other threads to acquire it.

synchronized(obj) {
obj.wait();
}

✅ notify()

Definition:
• Wakes up one thread that is waiting on the object’s monitor (from a wait() call).

Key Points:
• Like wait(), it must be used in a synchronized block.
• The awakened thread still needs to reacquire the object’s lock before continuing.

synchronized(obj) {
obj.notify();
}

✅ notifyAll()

Definition:
• Wakes up all threads waiting on the object’s monitor.

Use Case:

Used when multiple threads might be waiting and you want to notify all of them.

synchronized(obj) {
obj.notifyAll();
}

🔁 How They Work Together

In a producer-consumer problem:
• The consumer might wait() if the queue is empty.
• The producer adds items and calls notify() to wake up the consumer.



⚠️ Important Notes:
• wait(), notify(), and notifyAll() are methods of java.lang.Object, not Thread.
• You can’t call them on a Thread instance unless it’s inside a synchronized block on that same object.
• Misuse can lead to deadlocks or spurious wakeups, so consider using java.util.concurrent classes (e.g., Lock, Condition, BlockingQueue) in production code.

Thank you!

17/05/2025

How do you prevent deadlock in Java?

Preventing deadlock in Java requires understanding how it happens and then applying strategies to avoid the four conditions that lead to deadlock.



🔄 What Causes Deadlock?

A deadlock occurs when:
1. Mutual exclusion – Only one thread can use a resource at a time.
2. Hold and wait – A thread holds one resource and waits for another.
3. No preemption – Resources can’t be forcibly taken.
4. Circular wait – A closed chain of threads exists where each thread holds one resource and waits for another.

All four must be present for a deadlock to occur.



✅ Strategies to Prevent Deadlock in Java

1. Avoid Nested Locks
• Don’t acquire multiple locks at once if you can avoid it.

synchronized (lock1) {
synchronized (lock2) { // Dangerous: could cause circular wait
// ...
}
}

2. Lock Ordering
• Always acquire locks in a fixed global order.

Object lockA = new Object();
Object lockB = new Object();

// Always lock lockA first, then lockB
synchronized (lockA) {
synchronized (lockB) {
// critical section
}
}

3. Try-Lock with Timeout (Using ReentrantLock)
• Use tryLock() from java.util.concurrent.locks.ReentrantLock to avoid waiting indefinitely.

ReentrantLock lock1 = new ReentrantLock();
ReentrantLock lock2 = new ReentrantLock();

if (lock1.tryLock(1, TimeUnit.SECONDS)) {
try {
if (lock2.tryLock(1, TimeUnit.SECONDS)) {
try {
// work with both locks
} finally {
lock2.unlock();
}
}
} finally {
lock1.unlock();
}
}

4. Use a Lock Timeout and Detect Stalls
• Implement your own timeout or monitoring logic to detect and interrupt threads stuck too long.

5. Avoid Unnecessary Locks
• Reduce lock granularity—use synchronized blocks only around code that absolutely needs it.

6. Use Higher-Level Concurrency Tools
• Instead of managing low-level locks, use thread-safe collections or classes from java.util.concurrent like:
• ConcurrentHashMap
• ExecutorService
• Semaphore
• CountDownLatch



🛠️ Example Scenario – Potential Deadlock

Thread 1: Thread 2:
synchronized (A) { synchronized (B) {
synchronized (B) { synchronized (A) {
} }
}

Fix: Ensure both threads lock in the same order (e.g., always lock A before 😎.

Thank You!

11/05/2025

What is synchronization?

Synchronization in Java is a technique used to control access to shared resources by multiple threads, preventing data inconsistency and race conditions.

Why is it needed?

When multiple threads access the same object or variable simultaneously, they might interfere with each other. This can lead to unexpected behavior or corrupted data.

How does it work?

Java provides the synchronized keyword to ensure that only one thread at a time can access a block of code or method that modifies shared data.

Types of Synchronization:
1. Synchronized Method

public synchronized void increment() {
count++;
}

• The whole method is locked for one thread at a time.

2. Synchronized Block

public void increment() {
synchronized(this) {
count++;
}
}

• Locks only the specified part of the code for better performance.

3. Static Synchronization
• Used for synchronizing static methods:

public static synchronized void print() { ... }

Monitor Locks

Every object in Java has a built-in lock (or monitor). When a thread enters a synchronized method/block, it acquires the lock for that object. Other threads must wait until the lock is released.

Example Scenario:

Imagine two threads withdrawing money from the same bank account at the same time. Without synchronization, they might both see the same balance and withdraw more than the account holds.

Thank you!

What is the purpose of try-catch-finally blocks?The try-catch-finally blocks in Java are used for exception handling—to ...
10/05/2025

What is the purpose of try-catch-finally blocks?

The try-catch-finally blocks in Java are used for exception handling—to gracefully handle runtime errors and ensure resources are managed properly.



1. try Block
• Contains code that might throw an exception.
• Only one try block is allowed per structure, but it can be followed by multiple catch blocks.

try {
int result = 10 / 0; // May throw ArithmeticException
}

2. catch Block
• Handles the exception thrown by the try block.
• You can have multiple catch blocks for different exception types.

catch (ArithmeticException e) {
System.out.println("Cannot divide by zero.");
}

3. finally Block
• Always executes, regardless of whether an exception is thrown or caught.
• Used to release resources like closing files, database connections, etc.

finally {
System.out.println("Cleanup code runs here.");
}

try {
int[] numbers = new int[5];
numbers[10] = 99; // Will cause ArrayIndexOutOfBoundsException
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Index out of bounds!");
} finally {
System.out.println("This will always execute.");
}

What is the difference between checked and unchecked exceptions?In Java, exceptions are divided into checked and uncheck...
10/05/2025

What is the difference between checked and unchecked exceptions?

In Java, exceptions are divided into checked and unchecked exceptions based on how the compiler enforces error handling.



1. Checked Exceptions
• Definition: Exceptions that are checked at compile-time.
• Requirement: The code must either handle them using a try-catch block or declare them using the throws keyword.
• Examples:
• IOException
• SQLException
• FileNotFoundException

public void readFile(String file) throws IOException {
FileReader reader = new FileReader(file);
}

2. Unchecked Exceptions
• Definition: Exceptions that are not checked at compile-time.
• Requirement: The compiler doesn’t force you to handle or declare them.
• Examples:
• NullPointerException
• ArrayIndexOutOfBoundsException
• IllegalArgumentException

public void divide(int a, int b) {
int result = a / b; // May throw ArithmeticException
}

10/05/2025

What are the different types of class loaders?

In Java, ClassLoaders are responsible for dynamically loading classes into the Java Virtual Machine (JVM) at runtime. There are several types of class loaders, each with a specific purpose. Here are the main types:



1. Bootstrap ClassLoader (Primordial ClassLoader)
• Loads: Core Java classes (e.g., java.lang.*, java.util.*) from the /lib directory.
• Implemented in: Native code (not Java).
• Parent: None (it’s the root of the class loader hierarchy).



2. Extension ClassLoader (Platform ClassLoader in Java 9+)
• Loads: Classes from the /lib/ext directory or any other location specified by the java.ext.dirs system property.
• Parent: Bootstrap ClassLoader.
• Java 9+ Note: Now called Platform ClassLoader and has broader responsibilities.



3. System/Application ClassLoader
• Loads: Classes from the application classpath (i.e., paths specified via the -cp or CLASSPATH environment variable).
• Parent: Extension ClassLoader.
• Most common: This is the class loader used to load your own application classes.



4. Custom ClassLoader
• User-defined: You can create your own class loader by extending the ClassLoader class.
• Used for: Custom class loading strategies (e.g., loading encrypted classes, loading classes from a database or network).
• Parent: Can be explicitly defined.



ClassLoader Hierarchy (Delegation Model)

Bootstrap ClassLoader

Extension/Platform ClassLoader

System/Application ClassLoader

Custom ClassLoader (if any)

Java uses a parent delegation model—each class loader delegates class loading to its parent before attempting to load the class itself.

Thank you!

07/05/2025

How Does Java Achieve Platform Independence?

Java achieves platform independence through the use of the Java Virtual Machine (JVM) and the bytecode format.

1. Java Code Compilation:
• Java source code (.java) is compiled by the Java compiler (javac) into an intermediate form called bytecode (.class files).
• This bytecode is not specific to any hardware or operating system.
2. Bytecode Ex*****on by JVM:
• The compiled bytecode is executed by the Java Virtual Machine (JVM).
• The JVM acts as an abstraction layer between the bytecode and the underlying platform (Windows, Linux, Mac, etc.).
3. JVM Availability on Multiple Platforms:
• Each platform has its own implementation of the JVM.
• As long as a JVM is available for a platform, the same Java bytecode can run unchanged on that platform.

public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello, world!");
}
}

• Compiled to: HelloWorld.class (bytecode)
• Run with: java HelloWorld
• JVM on Windows/Linux/Mac interprets or JIT-compiles the bytecode to native code for that specific system.

Thank you!

07/05/2025

What are Memory Leaks in Java?

A memory leak in Java occurs when objects are no longer needed but the garbage collector (GC) cannot remove them because they are still being referenced by parts of the program. As a result, memory that should be reclaimed remains allocated, which can eventually lead to OutOfMemoryError.

Common Causes of Memory Leaks:
1. Static references to objects:
Objects held in static fields will stay in memory as long as the class is loaded.
2. Unclosed resources:
Not closing resources like database connections, file streams, or sockets can hold memory longer than needed.
3. Listeners and callbacks:
If a listener is registered but never unregistered, it may keep a reference to an object longer than intended.
4. Improper use of collections:
Adding objects to collections (e.g., List, Map) and never removing them can lead to memory buildup.
5. Inner classes holding references:
Non-static inner classes implicitly hold a reference to their outer class, which can lead to leaks if not handled properly.

How to Avoid Memory Leaks in Java:
1. Use Weak References When Appropriate:
• Use WeakHashMap for cache-like structures.
• Use WeakReference or SoftReference for large objects you don’t want to prevent GC from collecting.
2. Remove Listeners and Observers:
• Always deregister listeners or callbacks once they’re no longer needed.
3. Close Resources Properly:
• Use try-with-resources for handling streams, readers, sockets, and database connections.

try (BufferedReader reader = new BufferedReader(new FileReader("file.txt"))) {
// use reader
} // reader is automatically closed

4. Avoid Static References to Large Objects:
• Don’t keep large objects in static fields unless absolutely necessary.
5. Profile and Monitor Memory:
• Use tools like VisualVM, Eclipse Memory Analyzer (MAT), or YourKit to identify memory leaks.
6. Limit Lifetime of Collections:
• Regularly clear unused data from collections (e.g., remove old entries from HashMap).

Thank you!

06/05/2025

What is the use of the transient keyword?

The transient keyword in Java is used to prevent a field from being serialized when an object is being converted to a byte stream, such as during serialization using ObjectOutputStream.

Why use transient?

Some fields of an object may contain sensitive information (like passwords) or may not be serializable (like a file handle or a thread). You can mark such fields as transient so they won’t be included in the serialized output.

Example:

import java.io.*;

class User implements Serializable {
String username;
transient String password; // will not be serialized

User(String username, String password) {
this.username = username;
this.password = password;
}
}

If you serialize and then deserialize a User object, the username will be restored, but password will be null.

Key Points:
• Only applies during Java serialization (e.g., using ObjectOutputStream).
• transient fields are skipped and get default values after deserialization.
• Useful for handling security-sensitive or non-serializable data.

Thank you!

Address

Indore
452010

Website

Alerts

Be the first to know and let us send you an email when Java Coder posts news and promotions. Your email address will not be used for any other purpose, and you can unsubscribe at any time.

Share