Skip to main content

Mid Java Interview Questions

Curated Mid-level Java interview questions for developers targeting mid positions. 20 questions available.

Last updated:

Java Interview Questions & Answers

Skip to Questions

Welcome to our comprehensive collection of Java interview questions and answers. This page contains expertly curated interview questions covering all aspects of Java, from fundamental concepts to advanced topics. Whether you're preparing for an entry-level position or a senior role, you'll find questions tailored to your experience level.

Our Java interview questions are designed to help you:

  • Understand core concepts and best practices in Java
  • Prepare for technical interviews at all experience levels
  • Master both theoretical knowledge and practical application
  • Build confidence for your next Java interview

Each question includes detailed answers and explanations to help you understand not just what the answer is, but why it's correct. We cover topics ranging from basic Java concepts to advanced scenarios that you might encounter in senior-level interviews.

Use the filters below to find questions by difficulty level (Entry, Junior, Mid, Senior, Expert) or focus specifically on code challenges. Each question is carefully crafted to reflect real-world interview scenarios you'll encounter at top tech companies, startups, and MNCs.

Questions

20 questions
Q1:

Explain the Java Memory Model (JMM).

Mid

Answer

Java Memory Model defines visibility, ordering, and atomicity rules.
Heap stores objects; Stack stores references and local variables.
Method area stores class metadata.
PC register tracks execution.
Garbage collector manages heap memory automatically.
Quick Summary: JMM defines rules for visibility and ordering of memory operations across threads. Without JMM rules, CPUs and compilers can reorder operations for optimization. Key rules: volatile read/write creates happens-before. Monitor unlock happens-before subsequent lock on same monitor. Thread start happens-before first action in started thread. These rules ensure correct behavior without locking everything.
Q2:

What is the role of JVM, JIT, and bytecode?

Mid

Answer

JVM executes Java bytecode across platforms.
Bytecode is the intermediate compiled code.
JIT compiler converts bytecode to native machine code at runtime for faster execution.
Quick Summary: JVM (Java Virtual Machine) executes bytecode and provides memory management, GC, and security. JIT (Just-In-Time) compiler optimizes hot methods at runtime - compiles frequently executed bytecode to native machine code. Bytecode is the compiled output of Java source - platform-independent intermediary. JIT makes Java nearly as fast as C++ for long-running applications by optimizing hot paths.
Q3:

Explain garbage collection algorithms in Java.

Mid

Answer

Mark-and-Sweep marks live objects and removes unused ones.
Generational GC optimizes by separating objects into young and old generations.
Stop-the-world pauses occur during GC phases.
Modern collectors like G1 and ZGC reduce latency.
Quick Summary: Java GC algorithms: Serial (single-threaded, for small heaps), Parallel/Throughput (multi-threaded GC, good for batch processing), CMS (Concurrent Mark Sweep - deprecated, low pause), G1 (default since Java 9 - region-based, balances throughput and latency), ZGC (Java 11+ - sub-millisecond pauses for huge heaps), Shenandoah (similar to ZGC). Choose based on your latency vs throughput requirements.
Q4:

What are soft, weak, and phantom references?

Mid

Answer

SoftReference cleared when memory is low; used for caching.
WeakReference cleared during GC if no strong references exist.
PhantomReference used for cleanup before object collection.
Quick Summary: Reference types control GC behavior. Strong reference (normal): GC never collects. Soft reference (SoftReference): GC collects only when memory is low - good for caches. Weak reference (WeakReference): GC collects at next GC cycle - useful for canonicalization maps. Phantom reference (PhantomReference): enqueued after object is collected - for cleanup after GC. WeakHashMap uses weak keys.
Q5:

Explain Java ClassLoaders.

Mid

Answer

ClassLoaders load classes dynamically at runtime.
Types: Bootstrap, Extension, System, and Custom loaders.
Enable modularity, dynamic behavior, and class reloading.
Quick Summary: ClassLoaders load class files into the JVM. Hierarchy: Bootstrap (loads core Java classes from rt.jar), Extension (loads ext/ directory classes), Application/System (loads your app's classpath). Parent delegation model: child loader asks parent first before loading itself - prevents duplicate loading and security exploits. Custom ClassLoaders enable hot reloading and plugins (OSGi, application servers).
Q6:

How do you implement multithreading optimizations?

Mid

Answer

Use immutable objects for thread safety.
Prefer concurrent collections and atomic variables.
Minimize synchronized blocks.
Use thread pools for efficient thread reuse.
Quick Summary: Multithreading optimizations: use thread pools (avoid thread creation overhead), prefer lock-free structures (AtomicInteger, ConcurrentHashMap), minimize lock scope (hold locks for shortest time possible), use volatile for simple visibility (cheaper than synchronized), avoid false sharing (pad objects to cache line size), prefer immutable objects (zero sync cost), and profile before optimizing.
Q7:

Explain the difference between process and thread in Java.

Mid

Answer

Process: Independent execution with separate memory.
Thread: Lightweight execution sharing memory within a process.
Threads improve concurrency; processes ensure isolation.
Quick Summary: Process: independent program with its own memory space, expensive to create and switch, communication via IPC. Thread: lightweight execution unit within a process, shares process memory (heap), cheap to create, communication via shared memory (but needs synchronization). Java threads share heap but each has its own stack, program counter, and registers.
Q8:

What is the difference between checked and unchecked exceptions in multithreaded contexts?

Mid

Answer

Checked exceptions must be declared or handled.
Unchecked exceptions do not require declaration.
Threads must handle exceptions internally; unhandled runtime exceptions terminate threads.
Quick Summary: In multithreaded code: checked exceptions in Callable.call() are wrapped in ExecutionException when retrieved via Future.get(). In Runnable.run(), checked exceptions must be caught internally or wrapped in RuntimeException. CompletableFuture.exceptionally() and handle() catch async exceptions. Thread.UncaughtExceptionHandler catches exceptions that escape thread run() methods.
Q9:

Explain the Singleton design pattern in Java.

Mid

Answer

Ensures one instance of a class exists.
Implement using eager loading, lazy loading, double-checked locking, or enum.
Provides global access to the instance.
Quick Summary: Singleton ensures only one instance of a class exists. Implementation: private constructor, static getInstance() method. Thread-safe options: eager initialization (static final field), synchronized getInstance() (slow), double-checked locking with volatile (fast, correct in Java 5+), or the enum singleton (simplest and thread-safe by JVM guarantee). Use dependency injection instead of Singleton where possible.
Q10:

Explain the Factory design pattern.

Mid

Answer

Factory pattern creates objects without exposing creation logic.
Promotes loose coupling and extensibility.
Used in dependency injection and plugin architectures.
Quick Summary: Factory pattern creates objects without exposing instantiation logic to the client. Factory Method: subclass decides which class to instantiate. Abstract Factory: family of related objects created together. Benefits: decouples creation from usage, easy to swap implementations, centralize creation logic. Spring's ApplicationContext is a factory - you ask for a bean, it creates/returns it.
Q11:

Explain the Observer design pattern.

Mid

Answer

Defines one-to-many relationship between objects.
Observers are notified automatically on state changes.
Useful for event-driven systems and GUIs.
Quick Summary: Observer pattern defines a one-to-many dependency. When one object (subject/observable) changes state, all registered observers are notified automatically. Java built-in: Observable class (deprecated), PropertyChangeListener. Modern approach: event buses (Guava EventBus), reactive streams (RxJava, Project Reactor). Used in GUI event handling, MVC pattern (model notifies views), messaging systems.
Q12:

Explain the Strategy design pattern.

Mid

Answer

Encapsulates algorithms into separate classes.
Allows changing behavior at runtime.
Improves flexibility and maintainability.
Quick Summary: Strategy pattern defines a family of algorithms, encapsulates each one, and makes them interchangeable. The context object holds a reference to a strategy interface and delegates work to it. Swap strategies at runtime. Example: sorting algorithms, payment processors, compression algorithms. In Java, lambdas are essentially Strategy objects for functional interfaces - replaces many traditional Strategy implementations.
Q13:

Explain the Decorator design pattern.

Mid

Answer

Adds behavior to objects dynamically without modifying class.
Promotes composition over inheritance.
Used in I/O streams and UI components.
Quick Summary: Decorator pattern adds behavior to an object dynamically without modifying its class or using inheritance. Wrap the original object in a decorator that adds functionality and delegates to the original. Stackable - wrap multiple decorators. Java I/O streams are classic decorators: BufferedInputStream wraps FileInputStream, adding buffering. Enables open/closed principle - extend behavior without modifying existing code.
Q14:

Explain the Adapter design pattern.

Mid

Answer

Converts interface of one class into another expected by client.
Enables integration of incompatible systems.
Useful for legacy code and third-party APIs.
Quick Summary: Adapter pattern makes incompatible interfaces work together. Creates a wrapper (adapter) that translates one interface into another. Object adapter: holds a reference to the adaptee, translates calls. Class adapter: extends the adaptee (rare in Java due to single inheritance). Example: java.io.InputStreamReader adapts InputStream (byte stream) to Reader (character stream) interface.
Q15:

Explain the Proxy design pattern.

Mid

Answer

Provides a surrogate object to control access to another object.
Used for lazy loading, security, caching, and remote proxies.
Quick Summary: Proxy pattern provides a surrogate that controls access to another object. Types: Virtual proxy (lazy initialization - create expensive object only when needed), Protection proxy (access control), Remote proxy (represents object in another JVM/network - Java RMI), Logging/caching proxy. Spring AOP uses dynamic proxies to add cross-cutting concerns (transactions, security, logging) without modifying your code.
Q16:

Explain Java volatile and its role in concurrency.

Mid

Answer

volatile ensures visibility of variable changes.
Prevents instruction reordering for that variable.
Does not guarantee atomicity for compound operations.
Quick Summary: volatile ensures a variable is read from and written to main memory, not a CPU-specific cache. Solves the visibility problem - one thread's write is immediately visible to all other threads. Does NOT guarantee atomicity - volatile int count++ is still a read-modify-write race condition (use AtomicInteger instead). Use volatile for simple flags (boolean running = true/false) and singleton double-checked locking.
Q17:

Explain Java Atomic classes.

Mid

Answer

Provide lock-free thread-safe operations.
Examples: AtomicInteger, AtomicBoolean, AtomicReference.
Faster than synchronized blocks for single-variable operations.
Quick Summary: Atomic classes (AtomicInteger, AtomicLong, AtomicBoolean, AtomicReference) provide lock-free thread-safe operations using CPU-level CAS (Compare-And-Swap). compareAndSet(expected, newValue) atomically updates only if current value matches expected - retries on failure. Faster than synchronized for simple counter/flag scenarios because no thread blocking. Used for high-performance counters and accumulators.
Q18:

What are Java locks and ReentrantLocks?

Mid

Answer

Locks provide advanced synchronization features.
ReentrantLock allows same thread to re-acquire lock.
Supports fairness, tryLock, timed locking, and conditions.
Quick Summary: ReentrantLock provides more control than synchronized: tryLock() (non-blocking attempt with optional timeout), lockInterruptibly() (can be interrupted while waiting), fair mode (threads acquire in order of waiting), and separate Condition objects (like multiple wait/notify queues). More powerful than synchronized but more verbose. Prefer synchronized for simple cases, ReentrantLock for advanced scenarios.
Q19:

How does Java handle thread pools?

Mid

Answer

ExecutorService manages thread pools.
Reduces overhead of thread creation.
Supports scheduled and concurrent task execution.
Quick Summary: Java thread pools (ExecutorService) reuse threads for multiple tasks. ThreadPoolExecutor core params: corePoolSize (always kept alive), maximumPoolSize (max threads), keepAliveTime (idle thread timeout), and BlockingQueue (task queue). When queue is full and max threads reached, RejectedExecutionHandler kicks in. Use Executors factory for common configurations, ThreadPoolExecutor for custom.
Q20:

Explain Java memory optimization strategies.

Mid

Answer

Use primitive types when possible.
Avoid unnecessary object creation.
Apply lazy initialization and caching.
Choose efficient collections.
Minimize object retention to help GC.
Quick Summary: Java memory optimization: use primitives instead of wrappers where possible, avoid unnecessary object creation, reuse objects (object pools for expensive objects), use StringBuilder instead of String concatenation in loops, be aware of autoboxing in collections, use weak/soft references for caches, tune GC with appropriate heap sizes and GC algorithm for your workload.

Curated Sets for Java

No curated sets yet. Group questions into collections from the admin panel to feature them here.

Ready to level up? Start Practice