or

Java Interview Questions

17 questions · Core Java and Spring Boot, freshers to senior

Java interviews usually start with core concepts and move quickly into Spring Boot and real project questions. These are grouped by experience level, with a short note on what a good answer covers.

Practise these out loud with AI

Freshers (0โ€“2 years)

Practise this level
  1. 1. What are the four pillars of OOP? Give an example of each.

    What they look for: Encapsulation, inheritance, polymorphism, abstraction. Use one small example from your own code, not textbook animals.

    Recommended Answer:
    Java achieves platform independence via the JVM (Java Virtual Machine). Source code (.java) is compiled into universal Bytecode (.class) by javac. The JVM then interprets or compiles (via JIT) this bytecode into machine-specific instructions for the host OS.
    // Compile: javac HelloWorld.java -> HelloWorld.class
    // Run:    java HelloWorld (Executed by JVM on Windows/Linux/Mac)
  2. 2. What is the difference between == and equals()?

    What they look for: == compares references; equals() compares content when overridden. Mention the equals and hashCode contract.

    Recommended Answer:
    String objects in Java are immutableโ€”any modification creates a new object in the String Constant Pool. StringBuilder is mutable and non-synchronized (faster, best for single-threaded string concatenation). StringBuffer is mutable and synchronized (thread-safe, but has synchronization overhead).
    // Efficient concatenation
    StringBuilder sb = new StringBuilder();
    for (int i = 0; i < 100; i++) sb.append(i);
    String result = sb.toString();
  3. 3. Why are Strings immutable in Java?

    What they look for: Security, thread safety, string pool reuse and safe use as HashMap keys.

    Recommended Answer:
    1. Encapsulation: Bundling data and methods into a single class with private variables and public getters/setters.
    2. Inheritance: Code reuse where a child class inherits properties from a parent class using 'extends'.
    3. Polymorphism: Performing a single action in different ways (Compile-time via Overloading, Runtime via Overriding).
    4. Abstraction: Hiding internal implementation and showing only functionality using abstract classes and interfaces.
  4. 4. What is the difference between ArrayList and LinkedList?

    What they look for: Array-backed versus node-based. Explain when each is faster, and that ArrayList is the usual default.

    Recommended Answer:
    Checked exceptions are checked at compile-time and must be handled using try-catch or declared with 'throws' (e.g., IOException, SQLException). Unchecked exceptions occur at runtime and inherit from RuntimeException (e.g., NullPointerException, ArrayIndexOutOfBoundsException, ArithmeticException).
  5. 5. How does a HashMap work internally?

    What they look for: Hashing into buckets, collisions, and treeification of long buckets since Java 8. Mention why a good hashCode matters.

    Recommended Answer:
    == compares object memory references (whether two variables point to the exact same memory address). .equals() compares the actual values/content of the objects if properly overridden (e.g., in String, Integer, or custom domain models).
    String s1 = new String("hello");
    String s2 = new String("hello");
    System.out.println(s1 == s2);      // false (different memory)
    System.out.println(s1.equals(s2)); // true (same content)
  6. 6. What is the difference between checked and unchecked exceptions?

    What they look for: Checked must be declared or handled; unchecked extend RuntimeException. Give an example of each.

    Recommended Answer:
    A HashMap in Java stores key-value pairs using hashing. It uses an internal array of Node buckets. When put(key, value) is called, it calculates hash(key) to find the bucket index. If collisions occur, it chains elements in a linked list; in Java 8+, if a bucket exceeds 8 nodes, it transforms into a Red-Black Tree (O(log n) lookup).
    Map<String, Integer> map = new HashMap<>();
    map.put("MockVora", 100);
    int score = map.getOrDefault("MockVora", 0);

Mid-level (2โ€“5 years)

Practise this level
  1. 7. How does Spring Boot auto-configuration work?

    What they look for: Conditional beans based on the classpath and properties. Mention how you would override or disable one.

    Recommended Answer:
    Garbage Collection automatically frees heap memory occupied by unreachable objects. The JVM divides heap memory into Young Generation (Eden, S0, S1) and Old (Tenured) Generation. New objects are born in Eden; survivors of Minor GC rounds move to Old Gen. Major/Full GC runs less frequently to clean Old Gen. Common collectors include G1GC, ZGC, and Shenandoah.
  2. 8. What is the difference between @Component, @Service and @Repository?

    What they look for: All are Spring beans; the names signal intent, and @Repository also translates persistence exceptions.

    Recommended Answer:
    1. Thread Pools: Use ExecutorService instead of manually creating threads.
    2. volatile: Guarantees visibility of variable updates across threads without locks.
    3. synchronized: Mutual exclusion lock on methods or blocks.
    4. Concurrent Collections: Use ConcurrentHashMap or CopyOnWriteArrayList instead of synchronized maps.
    ExecutorService executor = Executors.newFixedThreadPool(4);
    executor.submit(() -> processBatch());
    executor.shutdown();
  3. 9. What is the N+1 query problem in JPA and how do you fix it?

    What they look for: One query for parents plus one per child. Fix with fetch joins, entity graphs or batch fetching.

    Recommended Answer:
    In Spring, Inversion of Control (IoC) delegates object creation and lifecycle management to the Spring IoC Container. Dependency Injection (DI) is the design pattern implementing IoC, where dependencies are injected into a bean via Constructor Injection (recommended), Setter Injection, or Field Injection (@Autowired).
    @Service
    public class UserService {
      private final UserRepository repo;
      // Constructor injection (recommended)
      public UserService(UserRepository repo) {
        this.repo = repo;
      }
    }
  4. 10. How do you handle transactions in Spring?

    What they look for: @Transactional, propagation and rollback rules. Mention the self-invocation pitfall.

    Recommended Answer:
    1. @SpringBootApplication: Combines @Configuration, @EnableAutoConfiguration, and @ComponentScan.
    2. @RestController: Combines @Controller and @ResponseBody for JSON REST endpoints.
    3. @GetMapping / @PostMapping: Route mapping.
    4. @Autowired: Injects beans.
    5. @Service / @Repository: Marks service layers and DAO layers for component scanning.
  5. 11. What is the difference between synchronized and a ReentrantLock?

    What they look for: Both give mutual exclusion; ReentrantLock adds tryLock, timeouts and fairness.

    Recommended Answer:
    1. FetchType.LAZY: Loads child entities on-demand only when accessed (recommended to avoid N+1 queries).
    2. Join Fetch: Use JPQL 'JOIN FETCH' to load parent and child together in a single query.
    3. EntityGraph: Declare eager loading per query without altering entity mapping.
    @Query("SELECT u FROM User u JOIN FETCH u.orders WHERE u.id = :id")
    User findUserWithOrders(@Param("id") Long id);
  6. 12. How do you design a REST API for a resource?

    What they look for: Resource-based URLs, correct HTTP methods and status codes, validation, pagination and versioning.

    Recommended Answer:
    Streams allow functional, declarative processing of collections. Key operations:
    - Intermediate: map(), filter(), sorted(), distinct() (Lazy execution)
    - Terminal: collect(), forEach(), reduce(), count() (Triggers processing)
    - CompletableFuture enables non-blocking async computations.
    List<String> names = users.stream()
      .filter(u -> u.getActive())
      .map(User::getName)
      .collect(Collectors.toList());

Senior (5+ years)

Practise this level
  1. 13. How does garbage collection work in the JVM, and how would you tune it?

    What they look for: Generational heaps, G1 as default, and tuning only after measuring with GC logs.

  2. 14. How do services communicate in your microservices setup, and how do you handle failures?

    What they look for: REST or messaging, timeouts, retries with backoff, circuit breakers, and idempotency.

  3. 15. How would you find a memory leak in production?

    What they look for: Heap dumps, profilers, and looking for growing caches, static collections or unclosed resources.

  4. 16. How do you keep data consistent across microservices?

    What they look for: Avoid distributed transactions; use sagas, outbox pattern and eventual consistency where acceptable.

  5. 17. What are virtual threads and when would you use them?

    What they look for: Lightweight threads from Java 21 for high-concurrency blocking I/O. Mention pinning pitfalls with synchronized blocks.

Frequently asked questions

Which Java version should I prepare for?

Most companies run Java 17 or 21. Know features like records, switch expressions and virtual threads.

Is Spring Boot mandatory for Java interviews?

For backend roles, almost always. Core Java alone is usually enough only for fresher roles.

Do Java interviews include DSA?

Product companies usually include a DSA round. Service companies focus more on Java, Spring and project questions.

More interview questions