Skip to main content

Java Interview Cheat Sheet

Top 50 interview questions with concise answers. Print this page or save as PDF for offline study.

View All Java Questions

1. What are the main features of Java?

Java's main features: platform independence (write once, run anywhere via JVM), object-oriented, strongly typed, automatic memory management (garbage collection), multi-threading support, rich standard library, and robust exception handling. Java compiles to bytecode that runs on any JVM regardless of OS or hardware.

2. What is the difference between JDK, JRE, and JVM?

JDK (Java Development Kit): full package for developing Java apps - includes compiler (javac), JRE, and dev tools. JRE (Java Runtime Environment): what end users need to run Java apps - includes JVM and standard libraries but no compiler. JVM (Java Virtual Machine): the engine that executes compiled bytecode. JDK contains JRE which contains JVM.

3. What is the difference between Java and C++?

Java vs C++: Java is interpreted (bytecode + JVM), C++ compiles to native machine code. Java has automatic garbage collection, C++ uses manual memory management. Java doesn't support multiple class inheritance (uses interfaces), C++ does. Java has no pointers (only references), C++ has full pointer arithmetic. Java is platform-independent, C++ is platform-specific by default.

4. Explain object-oriented programming concepts in Java.

Java OOP concepts: Encapsulation (bundle data and methods, control access via modifiers), Inheritance (a class extends another to reuse and extend behavior), Polymorphism (one interface, multiple implementations - method overriding at runtime), Abstraction (hide implementation details, expose only what's needed via abstract classes and interfaces).

5. What is a class and an object in Java?

A class is a blueprint/template that defines fields (data) and methods (behavior). An object is an instance of a class - created with the new keyword. Example: class Car defines color, speed, and drive(). Each Car object is a separate instance with its own color and speed values but shares the same class methods.

6. What are primitive and reference data types?

Primitive types (int, double, boolean, char, byte, short, long, float) store values directly in memory - fast, no object overhead. Reference types (String, arrays, objects) store a reference (memory address) to an object on the heap. Primitives can't be null; reference types can. Primitives are passed by value; object references are also passed by value (the reference, not the object).

7. What is the difference between method overloading and overriding?

Overloading: same method name, different parameter types or count, resolved at compile time. Overriding: subclass provides a different implementation of a parent class method with the same signature, resolved at runtime (dynamic dispatch). Overloading is compile-time polymorphism; overriding is runtime polymorphism. Use @Override annotation to ensure you're actually overriding.

8. What are constructors in Java?

A constructor is a special method that initializes a new object. Same name as the class, no return type. Called automatically when you use new. If you don't define one, Java provides a default no-arg constructor. You can have multiple constructors (constructor overloading). Use this() to call another constructor in the same class.

9. What is the difference between this and super keywords?

this refers to the current class instance - used to distinguish instance variables from local variables, or call other constructors (this()). super refers to the parent class - used to call parent class methods (super.method()), access parent fields (super.field), or call the parent constructor (super()) - which must be the first line in the child constructor.

10. What are access modifiers in Java?

Access modifiers control visibility: private (only within the same class), default/package-private (no keyword - within the same package), protected (same package + subclasses), public (accessible everywhere). Rule of thumb: make fields private, methods public or package-private as needed. Use the most restrictive modifier that works for your use case.

11. What is the difference between static and instance members?

Static members belong to the class, not instances. Static fields are shared across all instances. Static methods can be called without creating an object (Math.sqrt()). Instance members belong to each object individually - each instance has its own copy of instance fields. Static methods can't access instance fields (no "this" available).

12. What is the difference between final, finally, and finalize?

final: variable can't be reassigned, method can't be overridden, class can't be extended. finally: block in try-catch that always runs (even if exception thrown) - used for cleanup (closing resources). finalize(): method called by GC before collecting an object - deprecated in Java 9, don't rely on it. All three are completely different concepts that happen to sound similar.

13. What is garbage collection in Java?

Java garbage collection automatically frees memory occupied by objects with no live references. The GC runs in the background, identifies unreachable objects, and reclaims their memory. You can't force GC (System.gc() is just a hint). Modern GC algorithms (G1, ZGC, Shenandoah) minimize pause times. Memory leaks happen when you keep references to objects you no longer need.

14. What are Java packages and their benefits?

Packages are namespaces that organize related classes. Benefits: avoid name collisions between classes in different libraries, control access (package-private visibility), and logical grouping makes code easier to navigate. Declare with "package com.example.model" at top of file. Import classes from other packages with "import". Java standard library uses java.util, java.io, java.lang etc.

15. What is an interface and how is it different from an abstract class?

Interface: defines a contract (method signatures), no instance fields (only constants), a class can implement multiple interfaces, methods are public abstract by default (Java 8+ allows default and static methods). Abstract class: can have concrete methods and instance fields, single inheritance only, use when related classes share common implementation. Choose interface for capabilities, abstract class for shared base implementation.

16. What are Java exceptions?

Exceptions are runtime errors that disrupt normal program flow. Checked exceptions (IOException, SQLException) must be caught or declared with throws - checked at compile time. Unchecked exceptions (RuntimeException, NullPointerException, ArrayIndexOutOfBoundsException) don't need to be explicitly handled. Use try-catch-finally to handle exceptions. Create custom exceptions by extending Exception or RuntimeException.

17. What is the difference between == and equals()?

== compares references (memory addresses) for objects - checks if two variables point to the same object. equals() compares content/value - should be overridden to define logical equality. "abc" == "abc" may be true (string pool) but new String("abc") == new String("abc") is false. Always use equals() to compare object values, use == only for primitives or reference identity checks.

18. What are wrapper classes and autoboxing/unboxing?

Wrapper classes (Integer, Double, Boolean etc.) wrap primitive types as objects so they can be used in collections and generics. Autoboxing: automatic conversion from primitive to wrapper (int to Integer). Unboxing: automatic conversion from wrapper to primitive. Watch out: unboxing a null Integer throws NullPointerException. Autoboxing in loops can create many short-lived objects.

19. What are Java generics and why are they used?

Generics allow you to write type-safe code that works with any type without casting. List instead of raw List. The compiler catches type mismatches at compile time. Type parameters are erased at runtime (type erasure) - the JVM sees raw types. Benefits: no need for explicit casting, compile-time type safety, reusable algorithms that work on any type.

20. What are Java collections?

Java Collections Framework provides reusable data structures. Core interfaces: List (ordered, allows duplicates), Set (no duplicates), Map (key-value pairs), Queue (FIFO), Deque (double-ended). Common implementations: ArrayList, LinkedList, HashSet, TreeSet, HashMap, TreeMap. Prefer List/Map/Set interfaces in variable types for flexibility. Use Collections utility class for sorting, searching, and synchronizing.

21. What are Java 8 Lambda expressions?

Lambda expressions are short anonymous functions. Syntax: (params) -> expression or (params) -> { statements }. Enables functional programming style. Used to implement functional interfaces (interfaces with one abstract method). Instead of anonymous inner class: Comparator c = (a, b) -> a.compareTo(b). Lambdas capture effectively final variables from the enclosing scope.

22. Explain functional interfaces.

Functional interfaces have exactly one abstract method (can have default and static methods). Annotate with @FunctionalInterface (optional but recommended). Built-in functional interfaces in java.util.function: Predicate (test, returns boolean), Function (apply, transforms T to R), Consumer (accept, takes T returns void), Supplier (get, returns T). Lambdas can be assigned to functional interfaces.

23. What is the Streams API in Java?

Streams API processes collections declaratively. Pipeline: source (list.stream()) -> intermediate operations (filter, map, sorted) -> terminal operation (collect, count, forEach). Lazy evaluation - intermediate ops only run when terminal op is called. Supports method chaining. Parallel streams: list.parallelStream(). Different from java.io streams - these are for processing sequences of data.

24. Difference between intermediate and terminal operations in Streams.

Intermediate operations are lazy - they don't execute until a terminal op is called and return a Stream. Examples: filter(), map(), flatMap(), sorted(), distinct(), limit(), peek(). Terminal operations trigger execution and produce a result or side effect. Examples: collect(), count(), forEach(), reduce(), findFirst(), anyMatch(), toList(). Only one terminal operation per stream pipeline.

25. Explain Optional in Java.

Optional is a container that may or may not contain a value - avoids null and NullPointerException. Create: Optional.of(value), Optional.ofNullable(valueOrNull), Optional.empty(). Consume: orElse(default), orElseGet(supplier), orElseThrow(), ifPresent(consumer), map(), flatMap(), filter(). Return Optional from methods that might not have a value. Don't use Optional as fields or method parameters.

26. What is method reference in Java 8?

Method references are shorthand for lambdas that call an existing method. Types: ClassName::staticMethod (Static), object::instanceMethod (Bound instance), ClassName::instanceMethod (Unbound instance), ClassName::new (Constructor). Example: list.forEach(System.out::println) instead of list.forEach(s -> System.out.println(s)). More readable when the lambda just calls one method.

27. Difference between map and flatMap in Streams.

map() transforms each element with a function that returns a single value - Stream becomes Stream. flatMap() transforms each element with a function that returns a Stream, then flattens all those streams into one - useful for one-to-many transformations. Example: stream of sentences, flatMap to words: sentences.stream().flatMap(s -> Arrays.stream(s.split(" "))).

28. Explain Collectors in Streams API.

Collectors are terminal stream operations that accumulate results. Common: Collectors.toList(), toSet(), toMap(), groupingBy() (group into Map>), partitioningBy() (split into two groups by predicate), joining() (concatenate strings), counting(), summingInt(), averagingInt(). Combine with downstream collectors: groupingBy(key, counting()) counts per group.

29. What are default and static methods in interfaces?

Default methods in interfaces provide a default implementation - existing implementing classes don't need to add it. Enables interface evolution without breaking backward compatibility. Static methods in interfaces are utility methods tied to the interface (like Collections methods for Collection). Used heavily in Java 8 to add Stream/Lambda support to existing collection interfaces without breaking code.

30. Explain the difference between sequential and parallel streams.

Sequential streams process elements one at a time in the current thread. Parallel streams split the work across multiple threads using the ForkJoinPool. Parallel can be faster for large datasets with CPU-intensive operations but adds overhead (splitting, merging, thread management). Parallel is harmful for: small collections, I/O operations, stateful operations, or when order matters with side effects.

31. How do Java 8 enhancements improve collection processing?

Java 8 collection enhancements: Iterable.forEach(consumer) - external loop. Collection.removeIf(predicate) - remove matching elements. List.sort(comparator). Map.forEach(), getOrDefault(), putIfAbsent(), computeIfAbsent(), merge(). Stream API for functional pipeline processing. These reduce boilerplate and enable more expressive collection processing without verbose loops.

32. How do you handle exceptions in lambda expressions?

Lambda bodies can only throw unchecked exceptions. To handle checked exceptions in lambdas: wrap in a try-catch inside the lambda, or create a helper functional interface that declares the checked exception, or use a utility method that wraps checked exceptions as unchecked. Alternatively, wrap the checked exception in a RuntimeException: e -> { try { ... } catch (IOException e) { throw new UncheckedIOException(e); } }

33. Difference between Predicate, Function, Consumer, and Supplier.

Predicate: test(T t) returns boolean - used for filtering. Function: apply(T t) returns R - transformation. Consumer: accept(T t) returns void - side effects. Supplier: get() returns T - produces values. BiFunction, BiConsumer, BiPredicate handle two arguments. UnaryOperator is Function. BinaryOperator is BiFunction. These cover most functional programming needs.

34. How do streams differ from traditional iteration?

Streams use internal iteration - you say what to do, the API handles how (can optimize, parallelize). Traditional iteration (for loop) uses external iteration - you control the loop. Streams are lazy (intermediate ops deferred), composable (chained pipelines), can be parallelized with one method call, and more declarative. Streams can only be consumed once - reuse the source to create a new stream.

35. How do you group elements using Collectors?

Collectors.groupingBy(classifier) groups stream elements into a Map>. Downstream collectors change the value: groupingBy(Person::getDept, counting()) gives Map. groupingBy(Person::getDept, toList()) is the default. Multi-level grouping: groupingBy(getDept, groupingBy(getCity)). toMap(keyMapper, valueMapper) for custom key-value extraction.

36. Explain the use of peek() in streams.

peek() is an intermediate operation that performs a side effect (like logging) for each element as it passes through, then passes the element unchanged to the next stage. Useful for debugging: stream.filter(x -> x > 0).peek(x -> log(x)).map(x -> x * 2). Don't use peek() to modify elements (it's for inspection only). Not guaranteed to run in all cases if terminal op short-circuits.

37. Difference between Optional.map() and Optional.flatMap().

Optional.map() applies a function to the contained value if present, wrapping the result in Optional. If empty, returns empty. Optional.flatMap() applies a function that itself returns Optional and doesn't double-wrap - used to chain Optional-returning methods. map is for non-Optional-returning functions, flatMap for Optional-returning functions (avoids Optional>).

38. Difference between immutable and unmodifiable collections.

Immutable collections (List.of(), Set.of(), Map.of() - Java 9+) can never be modified - add/remove/set throw UnsupportedOperationException and also disallow null elements. Unmodifiable collections (Collections.unmodifiableList()) are wrappers that reject mutations but the underlying collection can still be changed (through the original reference). Immutable is safer and allows more optimizations.

39. How do you handle nulls in streams?

Handle nulls in streams: filter() with Objects::nonNull to remove nulls before processing. Optional.ofNullable() to wrap potentially null values. map() handles nulls poorly - returns a stream with null elements that blow up on later operations. For map values: use getOrDefault() or computeIfAbsent(). Consider using Optional upstream to avoid nulls entering the stream at all.

40. What are the new Stream-related features in Java 9+?

Java 9+ stream features: takeWhile(predicate) takes elements while condition is true then stops. dropWhile(predicate) skips elements while condition is true then takes the rest. Stream.iterate(seed, hasNext, next) finite iterate with termination condition. Stream.ofNullable(value) returns empty stream for null. These fill gaps that required workarounds in Java 8.

41. Explain the four pillars of OOP in Java.

Four OOP pillars in Java: Encapsulation - wrap data and methods in a class, use private fields with public getters/setters. Inheritance - subclass extends superclass to reuse and add behavior (extends keyword). Polymorphism - object behaves differently based on actual type (method overriding). Abstraction - hide complex implementation behind simple interfaces (abstract classes, interfaces).

42. Difference between abstract classes and interfaces.

Abstract class: can have state (instance fields), constructors, concrete methods. Used for "is-a" relationships with shared implementation. A class can extend only one. Interface: no state (only constants), no constructors, all methods abstract by default (Java 8+ adds default/static). A class can implement many interfaces. Use abstract class for template base, interface for multiple capabilities/contracts.

43. What is method overriding vs method overloading?

Overriding: subclass replaces a parent method with the same name, return type, and parameters. Resolved at runtime - actual object type determines which method runs. Enables polymorphism. Overloading: same class has multiple methods with the same name but different parameters. Resolved at compile time based on argument types. Both are called polymorphism but at different times.

44. How does the super keyword work?

super refers to the parent class. super.method() calls the parent's version of an overridden method. super.field accesses a parent field hidden by a subclass field. super() in a constructor calls the parent constructor - must be the first statement. If you don't call super() explicitly, Java automatically inserts a call to the parent's no-arg constructor.

45. Explain constructor chaining in Java.

Constructor chaining calls one constructor from another in the same class using this(), or calls the parent constructor using super(). this() call must be the first line. Useful for avoiding code duplication when multiple constructors share setup logic. Chain to the most specific constructor: the others call it with default values.

46. What are static blocks and static methods?

Static blocks run once when the class is loaded by JVM, before any instance creation. Used for complex static field initialization. Static methods belong to the class (not instance), can be called without an object, but can only access static members. Instance initializer blocks run before each constructor. Static initialization order: parent class first, then child.

47. Difference between final, finally, and finalize.

final keyword: makes variable constant, method un-overridable, class un-extendable. finally block: always executes after try-catch, used to release resources (even if exception is thrown - except System.exit()). finalize() method: called by GC before reclaiming object memory - deprecated, unpredictable timing, don't use for cleanup. Use try-with-resources instead of finalize for resource cleanup.

48. Explain Java exception hierarchy.

Exception hierarchy: Throwable at top. Two branches: Error (serious system problems - OutOfMemoryError, StackOverflowError - don't try to catch these) and Exception. Exception branches into: checked exceptions (must handle - IOException, SQLException) and unchecked/RuntimeException (NullPointerException, IllegalArgumentException, ArrayIndexOutOfBoundsException). RuntimeExceptions typically indicate programming bugs.

49. How is multiple inheritance handled in Java?

Java doesn't support multiple class inheritance (a class can extend only one class) to avoid the diamond problem (ambiguous method resolution). Multiple interface inheritance is allowed - a class can implement many interfaces. Java 8 adds default methods to interfaces, handled with explicit override if two interfaces have conflicting defaults. This design simplifies inheritance while keeping flexibility.

50. Explain object cloning in Java.

Object cloning creates a copy of an object. Shallow clone (Object.clone()): copies primitive fields by value and reference fields by reference - both original and clone point to the same nested objects. Deep clone: recursively copies all nested objects too. Implement Cloneable interface and override clone(). Alternatively, use copy constructors or serialization for deep copying.
Ready to level up? Start Practice