โ˜• Java Interview Questions

Master Java interviews with questions on Core Java, Spring Framework, JVM internals, and design patterns

Core Java concepts, JVM internals, memory management, and fundamentals

โšก

15-Minute Java Cheatsheet

Quick reference for last-minute interview preparation

โ˜• Core Concepts

JVM: Bytecode โ†’ JIT โ†’ Machine code
Heap vs Stack: Objects vs primitives/refs
Pass by value: Always (refs copied, not objects)
Immutability: String, wrapper classes
final: Variable, method, class

๐Ÿ—๏ธ OOP Principles

Encapsulation: Private fields + public methods
Inheritance: extends (single), implements (multiple)
Polymorphism: Method overriding, overloading
Abstraction: Abstract classes, interfaces
Interface: Default methods (Java 8+), static methods

๐Ÿ“ฆ Collections Framework

List: ArrayList (O(1) access), LinkedList (O(1) insert)
Set: HashSet (O(1)), TreeSet (O(log n), sorted)
Map: HashMap (O(1)), TreeMap (sorted), LinkedHashMap (ordered)
Queue: PriorityQueue (heap), ArrayDeque
Thread-safe: ConcurrentHashMap, CopyOnWriteArrayList

โœจ Modern Java (8-21)

Lambda: (args) โ†’ expression
Stream API: filter, map, reduce, collect
Optional: Avoid null, orElse, orElseThrow
Records: Immutable data classes (Java 14+)
Virtual Threads: Lightweight concurrency (Java 21)

๐Ÿ”„ Concurrency

synchronized: Method or block level locking
volatile: Visibility guarantee, no caching
Executor: ThreadPoolExecutor, ForkJoinPool
CompletableFuture: Async programming
Locks: ReentrantLock, ReadWriteLock

๐Ÿงน Memory & GC

Heap: Young Gen (Eden, Survivor), Old Gen
GC Types: Serial, Parallel, G1, ZGC
Memory Leak: Static refs, listeners, inner classes
OutOfMemory: Heap, Metaspace, Stack
Profiling: jmap, jstack, VisualVM

๐Ÿƒ Spring Framework Essentials

IoC/DI: @Autowired, @Component, @Service, @Repository
Bean Scopes: Singleton (default), Prototype, Request, Session
AOP: @Aspect, @Before, @After, @Around
Boot: Auto-configuration, @SpringBootApplication
Data: JpaRepository, @Transactional
Security: Authentication, Authorization, JWT

โš ๏ธ Common Interview Gotchas

โ€ข == compares refs, .equals() compares content
โ€ข String pool: "abc" == "abc" but new String("abc") !=
โ€ข HashMap allows null key, Hashtable doesn't
โ€ข ArrayList default capacity: 10, grows by 50%
โ€ข static blocks run before constructor
โ€ข Checked vs Unchecked exceptions

String: Immutable class. Once created, the value cannot be changed. Any modification creates a new String object. Thread-safe because it's immutable.

StringBuilder: Mutable class. Values can be modified without creating new objects. Not thread-safe, but faster than StringBuffer.

StringBuffer: Mutable class like StringBuilder, but thread-safe (synchronized methods). Slower than StringBuilder due to synchronization overhead.

Java

Java 17 LTS Features:

  • Sealed Classes - restrict which classes can extend/implement them
  • Pattern Matching for switch (Preview)
  • Text Blocks for multi-line strings
  • Records - compact syntax for data classes
  • Enhanced Pseudo-Random Number Generators

Java 21 LTS Features:

  • Virtual Threads (Project Loom) - lightweight threads for high concurrency
  • Sequenced Collections - new interfaces for collections with defined order
  • Pattern Matching for switch (Standard)
  • Record Patterns - deconstruct record values
  • String Templates (Preview)
Java

The Singleton pattern ensures a class has only one instance and provides a global point of access to it. It's commonly used for logging, driver objects, caching, and thread pools.

Thread-Safe Implementations:

Java

Java's Garbage Collector automatically manages memory by reclaiming objects that are no longer reachable. The G1 (Garbage-First) GC is the default in Java 9+ and is designed for applications with large heaps.

G1GC Key Concepts:

  • Region-based: Heap is divided into equal-sized regions
  • Generational: Still uses Young/Old generation concepts
  • Concurrent: Most work happens concurrently with application threads
  • Predictable pause times: Aims to meet pause time goals
Java

G1GC JVM Flags:

bash

CompletableFuture is a powerful class for asynchronous programming, introduced in Java 8. It allows you to write non-blocking code and chain multiple asynchronous operations.

Java

HashMap: Not thread-safe. Multiple threads modifying it can cause inconsistencies or infinite loops.

ConcurrentHashMap: Thread-safe without synchronizing the entire map. Uses lock striping for better concurrency.

Java

Java Stream API provides a functional approach to process collections. Streams support lazy evaluation, parallel processing, and can significantly reduce boilerplate code.

Java

Generics enable types (classes and interfaces) to be parameters when defining classes, interfaces, and methods. They provide compile-time type safety and eliminate the need for casting.

Java

Java 8 introduced functional interfaces in java.util.function package. These are interfaces with a single abstract method (SAM) used with lambda expressions.

Java

OutOfMemoryError (OOM) occurs when JVM cannot allocate memory. Prevention is better than handling, but there are strategies for both.

Java

WeakHashMap is a Map implementation where keys are held with weak references. When a key has no strong references elsewhere, the entry can be garbage collected.

Java

Understanding time complexity of Java collections is crucial for choosing the right data structure and writing efficient code.

Java

The Executor framework provides a higher-level abstraction for managing threads, decoupling task submission from execution mechanics.

Java

Shutdown hooks are threads that run when JVM is shutting down, allowing cleanup of resources before the application terminates.

Java

These are fundamental OOP concepts that describe relationships between classes. Understanding them is crucial for good software design.

Java

Reflection allows inspection and modification of classes, interfaces, fields, and methods at runtime. It's used by frameworks like Spring, Hibernate, and JUnit for dependency injection, ORM, and testing.

Java

== compares object references (memory addresses) for objects, and values for primitives.equals() compares the actual content/values of objects.

Java

Java exceptions are divided into checked exceptions (must be handled), unchecked exceptions (RuntimeException), and errors. Proper exception handling improves code reliability and maintainability.

Java

๐Ÿง  Memory Management

JVM memory is divided into Heap (objects), Stack (method calls), Metaspace (class metadata), and native memory.

java
java

๐Ÿ”ฅ Core Java Fundamentals

Object-Oriented Programming (OOP) in Java is built on four fundamental principles: Encapsulation, Inheritance, Polymorphism, and Abstraction.

Java

Java provides robust multithreading support through the Thread class, Runnable interface, and the java.util.concurrent package for high-level concurrency utilities.

Java

Creating a custom Iterator requires implementing the Iterator interface with hasNext() and next() methods, handling the 2D structure with varying column sizes.

Java

SOLID is an acronym for five design principles that make software designs more understandable, flexible, and maintainable.

Java

Interview Tips for Java