Getting everything ready for you…

Loading courses, problems and your progress. This takes just a moment.

0s

Interview questions › Java

Java interview questions

1. What are the main features of Java?

Easy

Object-oriented, platform-independent (write once, run anywhere via JVM bytecode), robust (strong typing, exception handling, GC), secure, multithreaded, and has a huge standard library.

2. JDK vs JRE vs JVM?

Easy

JVM runs bytecode. JRE = JVM + core libraries needed to run Java programs. JDK = JRE + development tools (compiler javac, debugger, jar) needed to write Java programs.

3. How is Java platform independent?

Easy

javac compiles source into bytecode (.class), not machine code. Any device with a JVM can run that bytecode; the JVM translates it to native instructions (interpreter + JIT).

4. What is the JIT compiler?

Medium

The Just-In-Time compiler in the JVM compiles frequently executed ("hot") bytecode into native machine code at runtime, making Java programs much faster than pure interpretation.

5. Explain `public static void main(String[] args)`.

Easy

public so the JVM can call it from outside; static so it runs without creating an object; void returns nothing; main is the entry-point name; String[] args holds command-line arguments.

6. What are primitive data types in Java?

Easy

byte (1 byte), short (2), int (4), long (8), float (4), double (8), char (2, Unicode), boolean. Everything else is a reference type.

7. What are wrapper classes? What is autoboxing?

Easy

Wrapper classes (Integer, Double, Character…) wrap primitives as objects so they can be used in collections. Autoboxing converts primitive → wrapper automatically, unboxing does the reverse.

8. Why is String immutable in Java?

Medium

For security (strings hold URLs, file paths, credentials), thread safety, safe use as HashMap keys (hashCode can be cached), and to enable the String pool, where identical literals share one object.

9. String vs StringBuilder vs StringBuffer?

Easy

String is immutable. StringBuilder is mutable and fast but not thread-safe. StringBuffer is mutable and thread-safe (synchronized) but slower. Use StringBuilder for building strings in loops.

10. What is the String pool?

Medium

A special memory area in the heap where string literals are stored once and reused. String a = "hi"; String b = "hi"; point to the same object, while new String("hi") creates a new object.

11. == vs equals() in Java?

Easy

== compares references (memory addresses) for objects and values for primitives. equals() compares content when overridden (String, wrapper classes).

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

Easy

final is a modifier (constant variable, non-overridable method, non-extendable class). finally is a block that always runs after try/catch. finalize() was a method called by the GC before reclaiming an object — deprecated now.

13. What is exception handling?

Easy

A mechanism to handle runtime errors using try, catch, finally, throw and throws, so the program can recover or fail gracefully instead of crashing.

14. Checked vs unchecked exceptions?

Easy

Checked exceptions (IOException, SQLException) are checked at compile time and must be caught or declared with throws. Unchecked exceptions (RuntimeException subclasses like NullPointerException, ArithmeticException) are not checked at compile time.

15. throw vs throws?

Easy

throw is used inside a method to actually throw an exception object. throws is used in a method signature to declare which checked exceptions it may throw to the caller.

16. What is try-with-resources?

Medium

A try (Resource r = ...) statement that automatically closes resources implementing AutoCloseable (files, connections) when the block ends, even if an exception occurs.

17. What is the Java Collections Framework?

Easy

A set of interfaces and classes for storing groups of objects: List (ArrayList, LinkedList), Set (HashSet, LinkedHashSet, TreeSet), Queue/Deque (PriorityQueue, ArrayDeque) and Map (HashMap, LinkedHashMap, TreeMap).

18. ArrayList vs LinkedList?

Easy

ArrayList uses a dynamic array: O(1) random access, slow inserts/removals in the middle. LinkedList uses a doubly linked list: O(1) insert/remove at known positions/ends, O(n) access by index, more memory per element.

19. HashSet vs TreeSet vs LinkedHashSet?

Easy

HashSet: no order, O(1) average operations. LinkedHashSet: keeps insertion order. TreeSet: keeps elements sorted, O(log n) operations (Red-Black tree).

20. How does HashMap work internally?

Hard

It keeps an array of buckets. hashCode() of the key picks the bucket; entries with the same bucket form a linked list, converted to a balanced tree when it grows past 8 (Java 8+). equals() finds the exact key. When size exceeds capacity × load factor (0.75) the table doubles and entries are rehashed.

21. HashMap vs Hashtable vs ConcurrentHashMap?

Medium

HashMap is not synchronized and allows one null key. Hashtable is synchronized on every method (slow) and allows no nulls. ConcurrentHashMap is thread-safe with fine-grained locking/CAS, so it scales much better.

22. HashMap vs TreeMap?

Easy

HashMap has no ordering and O(1) average operations. TreeMap keeps keys sorted (or by a Comparator) with O(log n) operations and supports range queries like floorKey, ceilingKey.

23. Comparable vs Comparator?

Medium

Comparable defines the natural order inside the class via compareTo(). Comparator defines external, multiple orderings via compare() and is passed to sort methods (e.g. sort students by marks, then by name).

24. What is an Iterator? What is fail-fast?

Medium

An Iterator traverses a collection with hasNext(), next() and remove(). Fail-fast iterators (ArrayList, HashMap) throw ConcurrentModificationException if the collection is structurally modified during iteration (except through the iterator itself).

25. What are generics?

Medium

Generics let classes and methods work with any type while keeping compile-time type safety, e.g. List<String>. They avoid casts and ClassCastException. Java implements them with type erasure.

26. What is multithreading in Java? How do you create a thread?

Easy

Running multiple threads concurrently in one program. Create one by extending Thread (override run()) or implementing Runnable/Callable and passing it to a Thread or an ExecutorService. Call start(), not run().

27. What is the thread lifecycle?

Medium

New → Runnable → Running → Blocked/Waiting/Timed Waiting → Terminated.

28. What is synchronization?

Medium

Controlling access to shared resources so only one thread executes a critical section at a time, using synchronized methods/blocks or locks, preventing race conditions.

29. What is the volatile keyword?

Hard

volatile guarantees visibility: reads/writes go to main memory, so all threads see the latest value. It does not make compound operations like count++ atomic — use AtomicInteger or locks for that.

30. wait() vs sleep()?

Medium

wait() (Object method) releases the monitor lock and waits until notify()/notifyAll(); must be called inside synchronized code. sleep() (Thread method) pauses for a time but keeps any locks it holds.

31. What is a deadlock in Java and how to avoid it?

Medium

Two threads each hold a lock the other needs and wait forever. Avoid by acquiring locks in a consistent global order, using tryLock with timeouts, and keeping synchronized blocks small.

32. What is the ExecutorService?

Medium

A thread-pool framework (Executors.newFixedThreadPool(n)) that manages worker threads; you submit tasks (Runnable/Callable) and get Future results, instead of creating threads manually.

33. What is garbage collection?

Easy

The JVM automatically frees memory of objects that are no longer reachable. Heap generations (Young, Old) and collectors like G1 make it efficient. You can request it with System.gc() but it is not guaranteed.

34. Stack vs heap memory in Java?

Easy

The stack stores method frames, local primitives and references — per thread, fast, freed when the method returns. The heap stores all objects — shared by threads and managed by the garbage collector.

35. What are Java 8 features?

Easy

Lambda expressions, functional interfaces, Stream API, default and static methods in interfaces, Optional, method references and the new Date/Time API (java.time).

36. What is a lambda expression?

Easy

A short way to write an implementation of a functional interface: (a, b) -> a + b. It makes code concise, especially with collections and streams.

37. What is a functional interface?

Easy

An interface with exactly one abstract method, e.g. Runnable, Comparator, Predicate, Function. It can be implemented with a lambda; @FunctionalInterface enforces the rule.

38. What is the Stream API?

Medium

A way to process collections declaratively with a pipeline: list.stream().filter(x -> x > 5).map(x -> x * 2).collect(Collectors.toList()). Streams support lazy evaluation and parallel processing.

39. map() vs flatMap() in streams?

Medium

map transforms each element into exactly one element. flatMap transforms each element into a stream and flattens them into one stream (e.g. list of lists → single list).

40. What is Optional?

Easy

A container that may or may not hold a value, used to avoid NullPointerException and make "no result" explicit: findUser(id).orElse(defaultUser).

41. What is the transient keyword?

Medium

Marks a field to be skipped during serialization; after deserialization it gets its default value. Used for passwords or derived fields.

42. What is serialization?

Medium

Converting an object into a byte stream (to save to a file or send over the network) and back (deserialization). A class implements Serializable; serialVersionUID controls version compatibility.

43. What is reflection?

Hard

The ability to inspect and modify classes, methods and fields at runtime (Class.forName, getDeclaredMethods). Frameworks like Spring and JUnit rely on it.

44. What are the access modifiers in Java?

Easy

private (class only), default/package-private (same package), protected (same package + subclasses), public (everywhere).

45. Can we have multiple catch blocks? What is multi-catch?

Easy

Yes — more specific exceptions must come before general ones. Java 7 multi-catch handles several types in one block: catch (IOException | SQLException e).

46. What is the difference between an abstract class and interface in Java 8+?

Medium

Interfaces can now have default and static methods, but still cannot have instance state or constructors; a class can implement many interfaces but extend only one abstract class. Use abstract classes for shared state, interfaces for capabilities.

47. What is a static block?

Easy

A block static { ... } that runs once when the class is loaded, before main or any object creation — used to initialise static variables.

48. What is the difference between ClassNotFoundException and NoClassDefFoundError?

Hard

ClassNotFoundException is a checked exception thrown when loading a class by name at runtime (e.g. Class.forName) fails. NoClassDefFoundError is an error when a class present at compile time is missing at runtime.

49. What is the difference between ArrayList and Vector?

Easy

Both are resizable arrays. Vector is synchronized (thread-safe but slower) and grows by 100% when full; ArrayList is not synchronized and grows by 50%. Vector is legacy — use ArrayList, or Collections.synchronizedList/CopyOnWriteArrayList when thread safety is needed.

50. What is Spring Boot?

Easy

A framework built on Spring that makes it quick to create production-ready Java applications with auto-configuration, embedded servers (Tomcat), starter dependencies and minimal XML — widely used for REST APIs and microservices.

More topics