Java Interview Questions

Fundamentals

What is Java?

Java is a statically-typed, object-oriented language running on the JVM. Write once, run anywhere via bytecode and JIT compilation.

Runtime

JDK vs JRE vs JVM

JVM executes bytecode; JRE provides JVM + libraries to run apps; JDK adds compiler and tools to develop apps.

Types

Primitives vs Wrapper classes

Primitives (int, boolean) are value types; wrappers (Integer, Boolean) are objects. Autoboxing converts between them automatically.

Integer x = 5; // autobox
int y = x;      // unbox
Collections

Collections framework

Core interfaces: List, Set, Map. Implementations: ArrayList, LinkedList, HashSet, TreeSet, HashMap, TreeMap. Choose based on ordering, uniqueness, and performance.

Collections

List vs Set vs Map

List: ordered, allows duplicates. Set: unique elements, no index. Map: key-value pairs. Use HashMap for average O(1) lookup; TreeMap for sorted keys.

Types

Generics basics

Generics enable type-safe collections and APIs. Use wildcards (<?>, <? extends T>, <? super T>) to model variance.

List<String> names = new ArrayList<>();
List<? extends Number> nums; // read-only covariant
Error Handling

Checked vs Unchecked exceptions

Checked must be declared/handled (IOException); unchecked are runtime errors (NullPointerException). Prefer meaningful exception types and handle at boundaries.

Concurrency

Concurrency basics

Use threads, executors, and futures for parallelism. Synchronize shared state with synchronized blocks/locks; prefer high-level concurrency utilities.

ExecutorService pool = Executors.newFixedThreadPool(4);
Future<Integer> f = pool.submit(() -> 42);
Integer v = f.get();
Collections

Streams API

Declarative operations on collections: map, filter, reduce. Streams can be parallel; emphasize immutability and side-effect-free lambdas.

int sum = nums.stream().filter(n -> n % 2 == 0).mapToInt(n -> n).sum();
Runtime

Memory management & GC

GC reclaims unused objects automatically. Algorithms vary (G1, ZGC). Avoid memory leaks by releasing references and using weak references where appropriate.

Concurrency

Java Memory Model

Defines visibility and ordering of reads/writes across threads. Use volatile, locks, and happens-before relations to ensure correctness.

Object Model

equals and hashCode contract

Equal objects must have equal hashCodes; breaking the contract leads to incorrect behavior in hashed collections.

Best Practices

Immutability

Immutable objects are thread-safe and simpler to reason about. Use final fields and defensive copies.

Collections

Collectors and grouping

Use Collectors for grouping, partitioning, and summarizing stream results.

Tooling

Maven vs Gradle

Maven uses XML and conventions; Gradle is Groovy/Kotlin-based and more flexible. Both manage dependencies and builds.