54 questions - Fresher to experienced

Java interview questions and answers

Java interviews in service and product companies follow a pattern: core language and OOP, then collections (HashMap almost always), then Java 8 streams, exceptions and threads. Experienced rounds add Spring Boot and design questions.

Last updated:

Core Java

What is the difference between JDK, JRE and JVM?

The JVM runs compiled bytecode. The JRE is the JVM plus the standard libraries needed to run programs. The JDK is everything you need to develop: the JRE plus the compiler (javac) and tools. Since Java 11 the JDK is the usual download and a separate JRE is rarely shipped.

Why is Java called platform independent?

javac compiles source code to bytecode, not to machine code for one processor. Any machine with a JVM can run that bytecode. The JVM itself is platform specific; the bytecode is not.

What are the primitive types in Java?

There are eight: byte, short, int, long, float, double, char and boolean. They hold values directly, not references, and cannot be null. Each has a wrapper class, such as Integer for int, used in collections.

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

== compares references for objects: it checks whether both variables point to the same object. equals() compares content, if the class overrides it as String does. For primitives, == compares values.

String a = new String("java");
String b = new String("java");
System.out.println(a == b);      // false: two objects
System.out.println(a.equals(b)); // true: same text

Why is String immutable?

Once a String is created its value never changes. That makes it safe to share in the string pool, safe to use as a HashMap key because its hash cannot change, safe across threads, and safe for values such as file paths and URLs that are checked once and then used.

What is the difference between String, StringBuilder and StringBuffer?

String is immutable, so building text in a loop creates many objects. StringBuilder is mutable and fast. StringBuffer is also mutable but its methods are synchronized, which makes it slower; it is rarely needed today.

StringBuilder sb = new StringBuilder();
for (int i = 0; i < 3; i++) sb.append(i);
String result = sb.toString(); // "012"

What is autoboxing, and what is the Integer cache trap?

Autoboxing converts between primitives and wrappers automatically, such as int to Integer. Java caches Integer objects from -128 to 127, so == on two boxed values works inside that range by accident and fails outside it. Always compare wrappers with equals().

Integer a = 127, b = 127;
System.out.println(a == b); // true (cached)
Integer c = 128, d = 128;
System.out.println(c == d); // false
System.out.println(c.equals(d)); // true

What does final mean on a variable, a method and a class?

A final variable can be assigned only once. A final method cannot be overridden. A final class cannot be extended, as with String. A final reference cannot point to another object, but the object it points to can still change.

What is the difference between static and instance members?

A static field or method belongs to the class and is shared by all objects. An instance field belongs to each object. A static method cannot use this or read instance fields directly, because it runs without an object.

Is Java pass-by-value or pass-by-reference?

Always pass-by-value. For objects, the value passed is a copy of the reference. The method can change the object through that copy, but reassigning the parameter does not affect the caller's variable.

void rename(User u) {
  u.setName("Asha");   // caller sees this change
  u = new User("Ravi"); // caller does not see this
}

Object-oriented programming

What are the four pillars of OOP?

Encapsulation keeps data private behind methods. Inheritance lets a class reuse another class. Polymorphism lets one call behave differently depending on the object. Abstraction exposes what an object does and hides how.

What is the difference between overloading and overriding?

Overloading is several methods with the same name and different parameters in one class; the compiler picks one. Overriding is a subclass replacing a parent method with the same signature; the JVM picks one at runtime based on the actual object.

class Printer {
  void print(int x) {}
  void print(String s) {}   // overloading
}
class Animal { String sound() { return "..."; } }
class Dog extends Animal {
  @Override String sound() { return "Woof"; } // overriding
}

What is the difference between an abstract class and an interface?

A class can extend only one abstract class but implement many interfaces. An abstract class can have fields with state and constructors. An interface has constants, abstract methods and, since Java 8, default and static methods. Use an interface for a capability, and an abstract class for shared state and code in a family of classes.

What is runtime polymorphism?

A parent-type reference can point to a child object, and calling an overridden method runs the child's version. This is decided at runtime, which is why code written against List works with ArrayList and LinkedList alike.

Animal a = new Dog();
System.out.println(a.sound()); // "Woof"

Why does Java not allow multiple inheritance of classes?

To avoid the diamond problem: if two parents had the same method, the child would not know which to inherit. Interfaces can still clash through default methods, and then the class must override the method and choose explicitly.

What is the contract between equals() and hashCode()?

If two objects are equal by equals(), they must return the same hashCode(). If you override equals() and not hashCode(), HashMap and HashSet look in the wrong bucket and lose your objects. Unequal objects may share a hash code, but fewer collisions are faster.

@Override public boolean equals(Object o) {
  if (this == o) return true;
  if (!(o instanceof Point p)) return false;
  return x == p.x && y == p.y;
}
@Override public int hashCode() {
  return Objects.hash(x, y);
}

When would you prefer composition over inheritance?

Inheritance means "is a" and ties the child to every detail of the parent. Composition means "has a": the class holds another object and calls it. Composition is easier to change and test, so use inheritance only for a true is-a relationship.

Can a constructor be private?

Yes. A private constructor stops other classes from creating objects directly. It is used for singletons, for factory methods such as List.of, and for utility classes that only have static methods.

What does the super keyword do?

super refers to the parent class. super(...) calls a parent constructor and must be the first statement in a constructor. super.method() calls the parent version of an overridden method.

Collections

What are the main interfaces in the Collections framework?

List keeps order and allows duplicates. Set allows no duplicates. Queue and Deque hold elements for processing in order. Map stores key-value pairs and is not a Collection subtype. Common classes: ArrayList, HashSet, ArrayDeque, HashMap.

What is the difference between ArrayList and LinkedList?

ArrayList is backed by an array: get(i) is O(1), and inserting in the middle shifts elements. LinkedList is a doubly linked list: get(i) walks the list, but adding at the ends is cheap. In practice ArrayList is faster for almost everything because of memory locality.

How does HashMap work internally?

HashMap keeps an array of buckets. put() calculates the key's hash, picks a bucket, and stores the entry there. If keys collide, the bucket holds a list, and since Java 8 a long list (more than 8 entries, when the table has at least 64 buckets) becomes a balanced tree. get() finds the bucket by hash, then the key by equals(). When the map is 75% full (the default load factor) the array doubles and entries are spread out again.

What is the difference between HashMap, Hashtable and ConcurrentHashMap?

HashMap is not thread safe and allows one null key. Hashtable is synchronized on every method, allows no nulls, and is legacy. ConcurrentHashMap is thread safe with fine-grained locking, so threads rarely block each other; it allows no nulls either.

How does HashSet prevent duplicates?

HashSet is backed by a HashMap. Each element is stored as a key with a dummy value, so uniqueness comes from the key's hashCode() and equals(). Elements with a broken equals or hashCode can appear twice.

What is the difference between Comparable and Comparator?

Comparable is implemented by the class itself through compareTo() and defines its one natural order. Comparator is a separate object that defines any other order, so you can sort the same objects by name, then by age.

users.sort(Comparator.comparing(User::getName)
                     .thenComparing(User::getAge));

What is ConcurrentModificationException?

It is thrown by a fail-fast iterator when the collection is changed structurally while you loop over it, except through the iterator itself. Remove through Iterator.remove() or use removeIf.

// throws ConcurrentModificationException
for (String s : list) if (s.isEmpty()) list.remove(s);

// safe
list.removeIf(String::isEmpty);

What is the difference between HashMap, LinkedHashMap and TreeMap?

HashMap has no guaranteed order and O(1) average operations. LinkedHashMap keeps insertion order, or access order, which makes it a simple LRU cache. TreeMap keeps keys sorted and its operations are O(log n).

Exceptions

What is the difference between checked and unchecked exceptions?

Checked exceptions, such as IOException, must be caught or declared with throws; the compiler enforces it. Unchecked exceptions extend RuntimeException, such as NullPointerException, and usually mean a programming bug.

What is the difference between throw and throws?

throw actually throws an exception object inside a method. throws in a method signature declares which checked exceptions the method can pass to its caller.

Does the finally block always run?

It runs whether the try block ends normally, returns, or throws. It does not run if the JVM stops, for example through System.exit or a crash. Do not return from finally: it hides the original exception or return value.

What is try-with-resources?

It closes anything that implements AutoCloseable automatically at the end of the block, even if an exception is thrown. It replaces the old finally blocks full of close() calls.

try (BufferedReader in = Files.newBufferedReader(path)) {
  return in.readLine();
} // in.close() is called automatically

What is the difference between Error and Exception?

Both extend Throwable. An Exception is a condition the program can reasonably handle. An Error, such as OutOfMemoryError or StackOverflowError, signals a serious JVM problem that applications should not normally catch.

How do you create a custom exception?

Extend Exception for a checked exception or RuntimeException for an unchecked one, and pass the message and cause to super. Give it a name that says what went wrong, such as InsufficientBalanceException.

public class InsufficientBalanceException extends RuntimeException {
  public InsufficientBalanceException(String message) {
    super(message);
  }
}

Java 8 and later

What is a lambda expression?

A lambda is a short way to write an implementation of an interface that has one abstract method. It removes the boilerplate of anonymous classes.

Runnable task = () -> System.out.println("running");
Comparator<String> byLength = (a, b) -> a.length() - b.length();

What is a functional interface?

An interface with exactly one abstract method, which a lambda can implement. @FunctionalInterface makes the compiler check it. Common ones: Predicate (test), Function (apply), Consumer (accept), Supplier (get).

What is the Stream API?

Streams process a sequence of elements with a chain of operations such as filter, map and collect. They describe what to compute instead of writing loops, and they do not change the source collection.

List<String> names = employees.stream()
    .filter(e -> e.getSalary() > 50000)
    .map(Employee::getName)
    .sorted()
    .toList();

What is the difference between map and flatMap?

map turns each element into exactly one new element. flatMap turns each element into a stream and joins all of them into one flat stream, for example turning a list of orders into a stream of all their items.

What are intermediate and terminal operations?

Intermediate operations, such as filter, map and sorted, return a new stream and are lazy: nothing runs yet. A terminal operation, such as collect, count or forEach, starts the processing. A stream can be used only once.

What is Optional and how should you use it?

Optional is a container that may or may not hold a value. Use it as a return type to make "no result" explicit instead of returning null. Avoid calling get() without a check; use orElse, orElseThrow or map.

String city = findUser(id)
    .map(User::getCity)
    .orElse("Unknown");

What is a record?

A record, added in Java 16, is a short way to declare an immutable data class. The compiler writes the constructor, getters, equals, hashCode and toString for you.

public record Point(int x, int y) {}

Point p = new Point(2, 3);
System.out.println(p.x()); // 2

Multithreading and memory

What is the difference between Thread, Runnable and Callable?

Thread is the class that runs code in a new thread. Runnable is a task with no return value. Callable is a task that returns a value and can throw a checked exception. You usually submit Runnable or Callable tasks to an ExecutorService instead of creating threads yourself.

What does synchronized do?

synchronized lets only one thread at a time run the block or method for the same lock object. It also makes changes made inside the block visible to the next thread that takes the lock.

What does volatile guarantee?

volatile guarantees visibility: a write by one thread is seen by others immediately. It does not make compound actions atomic, so count++ on a volatile field is still a race. It suits simple flags such as a stop signal.

What is a race condition and how do you fix it?

A race condition happens when the result depends on the timing of threads, such as two threads reading and incrementing the same counter at once. Fix it with synchronized, a lock, or an atomic class.

AtomicInteger count = new AtomicInteger();
// safe from many threads
count.incrementAndGet();

Why use an ExecutorService instead of new Thread()?

Creating a thread per task is expensive and unbounded. An ExecutorService keeps a pool of reusable threads, queues extra tasks, and returns a Future so you can get results or cancel work.

ExecutorService pool = Executors.newFixedThreadPool(4);
Future<Integer> result = pool.submit(() -> compute());
Integer value = result.get();
pool.shutdown();

What is a deadlock and how do you avoid it?

A deadlock happens when two threads each hold a lock the other needs and both wait forever. Avoid it by always taking locks in the same order, holding locks for as short a time as possible, or using tryLock with a timeout.

What is the difference between stack and heap memory?

Each thread has its own stack for method calls, local variables and references. Objects live on the heap, which all threads share and the garbage collector manages. Deep recursion overflows the stack; too many live objects fill the heap.

How does garbage collection work?

The JVM frees objects that can no longer be reached from GC roots, such as live local variables and static fields. The heap is split into generations because most objects die young: they are collected cheaply in the young generation, and survivors are moved to the old generation. G1 has been the default collector since Java 9.

Can Java have memory leaks?

Yes. A leak happens when objects stay reachable after you stop needing them, so the collector cannot free them. Common causes are static collections that only grow, caches without limits, listeners never removed, and ThreadLocal values left on pooled threads.

Spring Boot basics

What is dependency injection in Spring?

Instead of a class creating its own dependencies with new, Spring creates the objects (beans) and passes them in. Constructor injection is the preferred style: dependencies are explicit, can be final, and are easy to replace in tests.

@Service
public class OrderService {
  private final PaymentClient payments;
  public OrderService(PaymentClient payments) {
    this.payments = payments;
  }
}

What does Spring Boot add on top of Spring?

Auto-configuration, which sets up beans based on the libraries on the classpath; starter dependencies, which bring in tested sets of libraries; an embedded server such as Tomcat, so the app runs as a plain jar; and production features through Actuator.

What is the difference between @Component, @Service, @Repository and @Controller?

All four mark a class as a Spring bean found by component scanning. @Service and @Controller are labels for the business and web layers. @Repository also translates database exceptions into Spring's DataAccessException types.

What is the difference between @Controller and @RestController?

@Controller methods usually return a view name for a template. @RestController combines @Controller and @ResponseBody, so every method's return value is written to the response body, usually as JSON.

What is the difference between @PathVariable and @RequestParam?

@PathVariable reads a value from the URL path, such as the 42 in /users/42. @RequestParam reads a query parameter, such as page in /users?page=2.

@GetMapping("/users/{id}")
User get(@PathVariable long id,
         @RequestParam(defaultValue = "false") boolean details) { ... }

Continue with another topic

Practise live

CrackInterviewAI listens to the live interview and gives a structured answer on screen for coding, system design, HR and project questions. Download for Windows.