Offer Ends Jan 10th : Get 100 Free Credits on Signup Claim Now

Interview Questions
December 8, 2025
14 min read

20 Java Interview Questions That Hiring Managers Actually Ask

20 Java Interview Questions That Hiring Managers Actually Ask

Forget memorizing trivia. We're breaking down the 20 core Java interview questions that reveal your true problem-solving skills and depth of knowledge.

Supercharge Your Career with CoPrep AI

I once interviewed a developer who could write flawless, complex algorithms on the whiteboard in minutes. I was impressed. Then I asked him a simple question: "Why did you choose an ArrayList here instead of a LinkedList?" He froze. He couldn't articulate the trade-offs. He had the 'what' down cold, but the 'why' was a complete mystery. He didn't get the job.

That's the secret nobody tells you about Java interviews. They aren't just about regurgitating facts. They're about demonstrating a deep, practical understanding of the tools you use every day. An interviewer wants to see your thought process. They want to know you can make sound architectural decisions, not just follow a tutorial.

This isn't just another list of questions. We're going to dissect what the interviewer is really asking, how to structure your answer, and the common traps to avoid. Let's get you ready for the real thing.

Part 1: The Bedrock - Core Java Concepts

These questions test your fundamental grasp of the Java language and platform. Get these wrong, and it's an immediate red flag.

1. Explain the difference between final, finally, and finalize.

  • What They're Really Asking: Do you understand Java's keywords for constants, error handling, and memory management? This is a classic filter question.
  • How to Answer:
    • final: A keyword used to apply restrictions. It can be used with variables (to create constants), methods (to prevent overriding), and classes (to prevent inheritance).
    • finally: A block used in a try-catch statement. The finally block always executes, whether an exception is thrown or not. It's crucial for cleanup code, like closing database connections or file streams.
    • finalize(): A method from the Object class. The garbage collector calls this method on an object just before reclaiming its memory. Stress that it's not guaranteed to run and should generally be avoided for resource cleanup in favor of try-with-resources or finally.

Pro Tip: Mentioning try-with-resources as the modern, preferred alternative to finally for resource management shows you're up-to-date with Java 7+ features.

2. Why are String objects immutable in Java?

  • What They're Really Asking: Do you understand the implications of immutability on security, performance, and concurrency?
  • How to Answer:
    • Security: Immutable strings are safe to pass around. For example, if you pass a String with a database username to a method, you know that method can't change it.
    • Performance: The String Pool is possible because strings are immutable. This saves memory by ensuring only one copy of a literal string like "hello" exists in the JVM.
    • Thread Safety: Immutability makes String objects inherently thread-safe. You can share them across multiple threads without worrying about synchronization issues.

3. Explain the contract between equals() and hashCode().

  • What They're Really Asking: Do you understand how hash-based collections like HashMap and HashSet work under the hood? This is a critical concept.
  • How to Answer:
    • State the core contract: If two objects are equal according to the equals() method, then they must have the same hashCode().
    • Explain the reverse is not true: If two objects have the same hashCode(), they are not necessarily equal. This is called a hash collision.
    • Provide the 'why': Hash-based collections use hashCode() to find the 'bucket' where an object should be stored. Then, they use equals() to find the exact object within that bucket. If you violate the contract, you won't be able to retrieve objects you've stored.

4. What is the JVM, JRE, and JDK?

  • What They're Really Asking: Do you know the basic architecture of the Java platform?
  • How to Answer:
    • JDK (Java Development Kit): The full package for developers. It includes the JRE, a compiler (javac), a debugger, and other development tools.
    • JRE (Java Runtime Environment): What you need to run Java applications. It contains the JVM and core libraries.
    • JVM (Java Virtual Machine): The abstract machine that executes Java bytecode. It's the component that provides platform independence (write once, run anywhere).

5. Explain Garbage Collection in brief.

  • What They're Really Asking: Do you have a high-level understanding of Java's automatic memory management?
  • How to Answer:
    • Garbage Collection (GC) is the process of automatically freeing up memory occupied by objects that are no longer in use by the application.
    • Mention the Heap is where objects live, and it's often divided into generations (like Young and Old Generation) to optimize GC.
    • Briefly describe the Mark and Sweep algorithm: First, the GC identifies all reachable objects (Mark). Then, it reclaims the memory used by unreachable objects (Sweep).

Part 2: Collections and Data Structures

This is where they test your ability to choose the right tool for the job. Performance often hinges on these decisions.

6. What's the difference between ArrayList and LinkedList?

  • What They're Really Asking: Do you understand the performance trade-offs between array-based and node-based data structures?
  • How to Answer: Use a table to make it clear.
FeatureArrayListLinkedList
Underlying StructureDynamic ArrayDoubly-Linked List (Nodes)
get(index) OperationO(1) - FastO(n) - Slow (must traverse)
add(element) OperationO(1) amortized (slow if resize needed)O(1) - Fast
add/remove in middleO(n) - Slow (requires shifting elements)O(1) - Fast (if you have the iterator)
Memory OverheadLowerHigher (due to node wrappers)

Key Takeaway: Choose ArrayList when you need fast, random access. Choose LinkedList when you'll be doing a lot of insertions and deletions in the middle of the list.

7. How does a HashMap work internally?

  • What They're Really Asking: This is a deeper dive into the equals()/hashCode() contract. Do you really get it?
  • How to Answer:
    • A HashMap stores key-value pairs in an array of 'buckets' or 'nodes'.
    • When you put(key, value), it first calculates the hashCode() of the key.
    • This hash is used to determine the index of the bucket in the array where the entry will be stored.
    • If the bucket is empty, the new entry is placed there. If not (a collision), the new entry is added to a list (or a balanced tree in Java 8+ for performance) at that bucket index. The equals() method is used to differentiate between keys in the same bucket.

8. What's the difference between Comparable and Comparator?

  • What They're Really Asking: Do you know how to define sorting logic for your custom objects?
  • How to Answer:
    • Comparable: Provides a single, natural ordering for a class. The class itself must implement the Comparable interface and its compareTo() method. For example, a Person class might be naturally ordered by age.
    • Comparator: Provides multiple, external orderings. You can create separate classes that implement the Comparator interface to define different ways to sort objects. For example, you could have one Comparator to sort Person objects by name and another to sort them by height.

9. Explain the Java Collections Framework hierarchy.

  • What They're Really Asking: Can you visualize the main interfaces and classes and understand their relationships?
  • How to Answer: Don't try to draw it. Describe the main branches:
    • The root is the Collection interface.
    • It has three main sub-interfaces: List (ordered, allows duplicates - ArrayList, LinkedList), Set (unordered, no duplicates - HashSet, TreeSet), and Queue (ordered for processing - PriorityQueue).
    • Mention that the Map interface is separate from the Collection hierarchy but is considered part of the framework. It deals with key-value pairs (HashMap, TreeMap).

Part 3: Concurrency and Multithreading

This is where senior developers separate themselves from juniors. These topics are complex but essential for building scalable applications.

10. What is the volatile keyword used for?

  • What They're Really Asking: Do you understand memory visibility issues between threads?
  • How to Answer:
    • The volatile keyword ensures that changes to a variable are always visible to other threads.
    • Normally, threads can have their own cached copy of a variable. Without volatile, one thread might update its copy, but another thread might not see that change.
    • volatile guarantees that any read of the variable will get the most recent write from main memory.
    • Crucially, it does not provide atomicity. For compound actions like count++, you still need synchronized or AtomicInteger.

11. What is the difference between synchronized and a ReentrantLock?

  • What They're Really Asking: Do you know the modern, more flexible ways to handle locking?
  • How to Answer:
    • synchronized: A built-in language feature (keyword). It's simpler to use. The lock is automatically acquired and released, even if exceptions occur.
    • ReentrantLock: A library-based class (java.util.concurrent.locks). It offers more flexibility:
      • Ability to attempt to acquire a lock without blocking (tryLock).
      • Ability to interrupt a thread waiting for a lock.
      • Fairness policies can be configured.
    • The main drawback of ReentrantLock is that you must manually release the lock in a finally block to avoid deadlocks.

12. Explain the lifecycle of a thread.

  • What They're Really Asking: Do you know the states a thread can be in?
  • How to Answer: List the key states:
    • NEW: The thread has been created but not yet started (new Thread()).
    • RUNNABLE: The thread is executing in the JVM. This includes both running and ready to run states.
    • BLOCKED: The thread is waiting to acquire a monitor lock (e.g., entering a synchronized block).
    • WAITING: The thread is waiting indefinitely for another thread to perform a particular action (e.g., after calling Object.wait()).
    • TIMED_WAITING: The thread is waiting for a specified period (e.g., after calling Thread.sleep()).
    • TERMINATED: The thread has completed its execution.

13. What is the Executor Framework?

  • What They're Really Asking: Do you know the modern way to manage threads instead of creating them manually?
  • How to Answer:
    • The Executor Framework (in java.util.concurrent) abstracts away thread creation and management.
    • Instead of new Thread(runnable).start(), you submit tasks (Runnable or Callable) to a thread pool.
    • This is much more efficient because it reuses existing threads, avoiding the overhead of creating new ones for every task.
    • Mention key classes like ExecutorService and factory methods in Executors (e.g., newFixedThreadPool).

Part 4: Frameworks and Ecosystem (Spring)

No Java developer works in a vacuum. These questions test your knowledge of the tools that build modern applications.

14. What is Dependency Injection (DI) and Inversion of Control (IoC)?

  • What They're Really Asking: Do you understand the core principle behind the Spring Framework?
  • How to Answer:
    • Inversion of Control (IoC): This is the broad principle where the control of object creation and lifecycle is transferred from your code to a container or framework.
    • Dependency Injection (DI): This is a specific implementation of IoC. Instead of your objects creating their own dependencies (e.g., new DatabaseService()), the framework injects these dependencies into your object at runtime.
    • The main benefit is loose coupling. Your components are easier to test and maintain because they don't depend on concrete implementations.

15. What's the difference between @Autowired and @Inject?

  • What They're Really Asking: A nuanced question to see if you know the difference between Spring-specific and standard Java annotations.
  • How to Answer:
    • Both are used for dependency injection.
    • @Autowired is Spring's own annotation.
    • @Inject is part of the Java Dependency Injection standard (JSR-330). It's more portable.
    • In a Spring project, they behave almost identically. The key difference is that @Autowired has a required attribute, which @Inject does not. Using @Inject is often seen as a best practice for framework-agnostic code.

16. What are Spring Boot Starters?

  • What They're Really Asking: Do you understand how Spring Boot simplifies configuration?
  • How to Answer:
    • Spring Boot Starters are a set of convenient dependency descriptors you can include in your project.
    • They solve the problem of dependency management. For example, including the spring-boot-starter-web dependency automatically pulls in everything you need for a web application: Tomcat, Spring MVC, Jackson for JSON, etc.
    • They enable auto-configuration, where Spring Boot will automatically configure beans based on the starters you have on your classpath.

17. What is Aspect-Oriented Programming (AOP)?

  • What They're Really Asking: Do you understand how Spring handles cross-cutting concerns?
  • How to Answer:
    • AOP is a programming paradigm that allows you to modularize cross-cutting concerns—logic that spans multiple points in an application.
    • Good examples are logging, security, and transaction management.
    • Instead of scattering this code everywhere, you define it in one place (an Aspect) and then declaratively apply it where needed (Pointcuts and Advice).

Part 5: System Design and Architecture

For mid-to-senior roles, you'll get questions that test your ability to think at a higher level.

18. How would you design a URL shortening service like TinyURL?

  • What They're Really Asking: Can you think through a full system? This tests your knowledge of APIs, databases, hashing, and scalability.
  • How to Answer: There's no single right answer. Walk through the components:
    • API Design: A POST /shorten endpoint that takes a long URL and returns a short URL. A GET /{shortCode} endpoint that redirects to the long URL.
    • Data Model: A simple database table with columns for short_code (primary key), long_url, created_at, etc.
    • Short Code Generation: How do you create the shortCode? You could use a hash function (like MD5 or SHA-1) on the long URL and take the first 6-8 characters. Discuss the possibility of collisions and how to handle them (e.g., retry with a slightly modified input).
    • Scalability: Discuss read vs. write load. Reads will be far more common. Mention using a cache (like Redis) to store popular short code to long URL mappings to reduce database hits.

19. What is the difference between REST and SOAP?

  • What They're Really Asking: Do you understand the fundamental approaches to building web services?
  • How to Answer:
    • SOAP (Simple Object Access Protocol): A standardized protocol. It's more rigid, often uses XML, and has built-in standards for security (WS-Security). It's more of a formal contract.
    • REST (Representational State Transfer): An architectural style, not a protocol. It's more flexible, lightweight, and typically uses JSON over HTTP. It leverages standard HTTP methods (GET, POST, PUT, DELETE). REST is the dominant style for modern web APIs.

20. Explain the CAP Theorem.

  • What They're Really Asking: Do you understand the fundamental trade-offs in distributed systems?
  • How to Answer:
    • The CAP Theorem states that a distributed data store can only provide two of the following three guarantees:
      • Consistency: Every read receives the most recent write or an error.
      • Availability: Every request receives a (non-error) response, without the guarantee that it contains the most recent write.
      • Partition Tolerance: The system continues to operate despite an arbitrary number of messages being dropped (or delayed) by the network between nodes.
    • In a modern distributed system, network partitions (P) are a fact of life, so you must choose between Consistency and Availability.
    • A CP system (like a relational database) will sacrifice availability to ensure every client has a consistent view.
    • An AP system (like many NoSQL databases) will sacrifice consistency to ensure the system is always available to respond, even if the data is slightly stale.

Remember, the goal isn't just to answer the question. It's to have a conversation that demonstrates your expertise and passion for building great software. Prepare your answers, but more importantly, understand the principles behind them. Good luck.

Tags

Java
Interview Questions
Java Developer
Software Engineering
Career Advice
Spring Boot
Coding Interview

Tip of the Day

Master the STAR Method

Learn how to structure your behavioral interview answers using Situation, Task, Action, Result framework.

Behavioral2 min

Quick Suggestions

Read our blog for the latest insights and tips

Try our AI-powered tools for job hunt

Share your feedback to help us improve

Check back often for new articles and updates

Success Story

N. Mehra
DevOps Engineer

The AI suggestions helped me structure my answers perfectly. I felt confident throughout the entire interview process!