Java Interview Questions and Answers

Java Interview Questions and Answers - EncodingCompiler

Quick answer

Java interviews usually move from the core language and OOP (classes, inheritance, polymorphism, interfaces) to strings, collections and HashMap internals, exceptions and concurrency, then the JVM: memory, garbage collection and class loading. Knowing modern Java, such as streams, records, sealed classes and virtual threads, shows you are current. These Java interview questions follow the same order, with short answers you can say out loud and code where it helps.

Java is still one of the most widely used languages for backend systems, Android, and enterprise software, and Java interviews follow a familiar path: core language and OOP first, then strings, collections, exceptions and concurrency, then the JVM and modern Java features. This guide covers the questions asked most often at each stage, with short answers and code. Below are the Java interview questions and answers that come up most often, with short explanations you can say out loud.

For the persistence side of Java, see our Hibernate and JPA interview questions.

Java Basics

Java interview questions and answers: JDK vs JRE vs JVM
JDK vs JRE vs JVM (quick reference)

1. What is Java?

Java is a general-purpose, object-oriented programming language and platform, released by Sun Microsystems in 1995 and now owned by Oracle. Java code is compiled to bytecode, which runs on the Java Virtual Machine, so the same compiled program runs on any operating system with a JVM. The reference implementation, OpenJDK, is open source.

2. What are the main features of Java?

  • Object-oriented: programs are built from classes and objects.
  • Platform-independent: compiled bytecode runs on any JVM (“write once, run anywhere”).
  • Automatic memory management: a garbage collector frees unused objects.
  • Strongly and statically typed: many errors are caught at compile time.
  • Robust and secure: no pointer arithmetic, bounds-checked arrays, and checked exceptions.
  • Multithreaded: concurrency is built into the language and libraries.
  • High performance: the JIT compiler turns frequently run bytecode into native code.
  • Rich standard library and a very large ecosystem of frameworks and tools.

3. Why is Java platform-independent?

The Java compiler, javac, turns source code into bytecode, a standard instruction set that is not tied to any processor or operating system. Each platform has its own JVM that runs that bytecode. So the compiled program is platform-independent, while the JVM itself is platform-specific.

4. What are the JDK, JRE and JVM?

  • JVM (Java Virtual Machine): loads, verifies and runs bytecode, manages memory, and performs JIT compilation. It is a specification, with implementations such as HotSpot and OpenJ9.
  • JRE (Java Runtime Environment): the JVM plus the standard class libraries, everything needed to run Java programs.
  • JDK (Java Development Kit): the JRE plus development tools such as the compiler (javac), debugger and jar, everything needed to build Java programs.

Since Java 11, Oracle and most vendors ship only the JDK, with no separate JRE download. You can build a slimmed-down runtime for an application with jlink.

5. How does Java achieve high performance?

The JVM starts by interpreting bytecode, while profiling which methods run most often. The Just-In-Time (JIT) compiler then compiles those “hot” methods to optimized native machine code, using what it has learned at runtime, for example inlining small methods. Modern garbage collectors and escape analysis also help. Long-running Java applications often perform close to natively compiled code.

6. Why is Java not 100% object-oriented?

Because of its eight primitive types, byte, short, int, long, float, double, char and boolean, which are plain values rather than objects. They exist for performance. Each has a wrapper class, such as Integer, and Java converts between them automatically, which is called autoboxing and unboxing. Static members, which belong to a class rather than an object, are another reason sometimes given.

7. What are access modifiers?

  • public: accessible from anywhere.
  • protected: accessible in the same package, and in subclasses in other packages.
  • Default (no modifier), also called package-private: accessible only within the same package.
  • private: accessible only within the same class.

Top-level classes can only be public or package-private.

8. What are packages, and why use them?

A package groups related classes and interfaces under a namespace, such as java.util or com.example.orders, and maps to a folder structure. Packages prevent name clashes between classes with the same name, support access control through package-private visibility, and make large codebases easier to navigate. Java has built-in packages from the standard library, and you create your own.

9. Why does Java not have pointers?

Java has references to objects, but not pointers you can manipulate. There is no pointer arithmetic and no direct memory access. That removes a whole class of bugs and security holes, such as buffer overflows and dangling pointers, and it lets the garbage collector move objects in memory safely.

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

For objects, == checks whether two references point to the same object. equals() checks whether two objects are logically equal, as defined by the class. For example, two different String objects containing “hello” are equals() but not ==. For primitives, == compares values. If you override equals(), you must also override hashCode(), so that equal objects have equal hash codes, or hash-based collections will misbehave.

11. What loops does Java have?

  • for: when you know how many times to loop.
  • Enhanced for (for-each): to go through every element of an array or collection.
  • while: checks the condition before each iteration.
  • do-while: runs the body at least once, then checks the condition.

Streams, from Java 8, are often used instead of loops for processing collections.

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

  • final is a keyword: a final variable cannot be reassigned, a final method cannot be overridden, and a final class cannot be extended.
  • finally is a block after try that always runs, whether or not an exception was thrown, typically for clean-up.
  • finalize() was a method the garbage collector could call before reclaiming an object. It was unreliable, was deprecated in Java 9, and is marked for removal. Use try-with-resources or Cleaner instead.

Object-Oriented Programming

13. What is object-oriented programming?

Object-oriented programming organizes software around objects, which combine data (fields) with the behavior that works on it (methods). Its four principles are encapsulation, inheritance, polymorphism and abstraction. It suits large programs that are maintained over time, because each object hides its details behind a clear interface.

14. What is a class, and what is an object?

A class is a blueprint that defines fields and methods. An object is an instance of a class, created with new, with its own copy of the fields.

public class Account {
    private final String owner;
    private double balance;

    public Account(String owner) {
        this.owner = owner;
    }

    public void deposit(double amount) {
        if (amount <= 0) throw new IllegalArgumentException("Amount must be positive");
        balance += amount;
    }

    public double getBalance() { return balance; }
}

Account acc = new Account("Asha");
acc.deposit(500);

15. What is encapsulation, and why does it matter?

Encapsulation means keeping an object’s fields private and exposing behavior through methods, as the Account class above does: the balance can only change through deposit(), which validates the amount. The benefit is control. The class can enforce its own rules, and its internal details can change without breaking the code that uses it.

16. What is inheritance, and what types does Java support?

Inheritance lets a class, the subclass, reuse and extend the fields and methods of another, the superclass, using extends. It models an “is-a” relationship: a SavingsAccount is an Account. Java supports single, multilevel and hierarchical inheritance between classes, but a class can extend only one class. Multiple inheritance of type is done with interfaces, since a class can implement many. Favor composition over inheritance when the relationship is “has-a” rather than “is-a”.

17. What is polymorphism?

Polymorphism means one interface with many implementations. Compile-time polymorphism is method overloading. Runtime polymorphism is method overriding: a variable of a parent type can refer to a subclass object, and the subclass’s version of the method runs.

18. What is the difference between overloading and overriding?

Overloading is defining several methods with the same name in one class but different parameter lists, resolved at compile time. Overriding is a subclass providing its own version of a method it inherited, with the same signature, resolved at runtime. Mark overriding methods with @Override, so the compiler catches mistakes.

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

An abstract class can have fields, constructors, and both abstract and implemented methods, and a class can extend only one. An interface defines a contract: since Java 8 it can include default and static methods, and since Java 9 private methods, but it cannot hold instance state, and a class can implement many interfaces. Use an interface to define a capability, and an abstract class to share code among closely related classes.

20. What does static mean?

A static member belongs to the class rather than to any object. A static field is shared by all instances, and a static method can be called without an object, but cannot use instance fields directly. Static blocks run once, when the class is loaded. Common uses are constants (static final), utility methods such as Math.max(), and factory methods.

Strings, Collections and Exceptions

Java interview questions and answers: Java Collections Cheat Sheet
Java Collections Cheat Sheet (quick reference)

21. Why are strings immutable?

Once a String is created, its value cannot change. Methods such as toUpperCase() return a new string. Immutability makes strings safe to share between threads, lets them be cached in the string pool, allows their hash codes to be cached, and protects values such as file paths and class names from being changed after a security check.

22. What is the string pool?

The string pool is a store, on the heap, of unique string literals. When code uses a literal such as "hello", the JVM reuses the existing pooled string if there is one, instead of creating another. new String("hello") always creates a new object outside the pool, and intern() returns the pooled version.

String a = "hello";
String b = "hello";
String c = new String("hello");

a == b;        // true: same pooled object
a == c;        // false: c is a separate object
a.equals(c);   // true: same characters

23. What is the difference between String, StringBuilder and StringBuffer?

String is immutable, so building a string in a loop with + creates many temporary objects. StringBuilder is mutable and fast, the right choice for building strings. StringBuffer is the older, synchronized version of StringBuilder, and is rarely needed.

24. What is the Java Collections Framework?

It is the set of interfaces and classes for storing groups of objects. The main interfaces are List (ordered, allows duplicates), Set (no duplicates), Queue and Deque (for processing in order), and Map (key-value pairs, which is not a subtype of Collection). Common implementations include ArrayList, LinkedList, HashSet, TreeSet, ArrayDeque, HashMap and TreeMap.

25. What is the difference between ArrayList and LinkedList?

ArrayList is backed by a resizable array: fast random access by index, and fast appends, but inserting or removing in the middle shifts elements. LinkedList is a doubly linked list: fast insertion and removal at the ends, but slow access by index, and more memory per element. In practice, ArrayList is the right default almost every time, and ArrayDeque is usually better than LinkedList as a queue.

26. How does HashMap work internally?

A HashMap stores entries in an array of buckets. To find a bucket, it uses the key’s hashCode(). If several keys land in the same bucket, a collision, they are stored together, and equals() finds the right one. Since Java 8, a bucket with many entries is converted from a linked list into a balanced tree, keeping lookups fast. When the map passes its load factor, 0.75 by default, it doubles its capacity and redistributes the entries. Lookups are close to constant time on average, but only if the keys have a good hashCode() and are not changed while they are in the map.

27. What is the difference between HashMap, LinkedHashMap, TreeMap and ConcurrentHashMap?

  • HashMap: no guaranteed order. Allows one null key.
  • LinkedHashMap: keeps insertion order, or access order, which is useful for simple caches.
  • TreeMap: keeps keys sorted. Lookups take logarithmic time.
  • ConcurrentHashMap: thread-safe, with high concurrency and no locking of the whole map. No null keys or values.

28. What is the difference between an Error and an Exception?

Both extend Throwable. An Error signals a serious problem the application usually should not try to handle, such as OutOfMemoryError or StackOverflowError. An Exception signals a condition the program can reasonably catch and recover from, such as FileNotFoundException or invalid input.

29. What is the difference between checked and unchecked exceptions?

Checked exceptions, subclasses of Exception but not of RuntimeException, such as IOException, must be caught or declared with throws, and the compiler enforces it. Unchecked exceptions, subclasses of RuntimeException, such as NullPointerException or IllegalArgumentException, usually signal programming errors and do not have to be declared.

30. What is try-with-resources?

Added in Java 7, try-with-resources automatically closes any resource that implements AutoCloseable, such as files, streams and database connections, when the block ends, even if an exception is thrown. It replaces error-prone finally blocks.

try (var reader = Files.newBufferedReader(Path.of("data.txt"))) {
    return reader.readLine();
}   // reader is closed automatically

Concurrency, Memory and the JVM

31. What is synchronization?

Synchronization controls access to shared data by multiple threads, so only one thread at a time runs a critical section. A synchronized method or block acquires the object’s monitor lock, which prevents race conditions and also guarantees that changes made by one thread are visible to the next thread that takes the lock. Higher-level tools in java.util.concurrent, such as ReentrantLock, atomic classes and concurrent collections, are often a better fit.

32. What does volatile do?

A volatile field is always read from and written to main memory, so every thread sees the latest value. It guarantees visibility but not atomicity: count++ on a volatile field is still not thread-safe. Use it for simple flags, such as a “stop” signal, and use AtomicInteger or locks for compound operations.

33. How do you create threads, and what is an ExecutorService?

You can extend Thread, or, better, pass a Runnable or Callable to a thread. In real applications you rarely create threads by hand. An ExecutorService manages a pool of threads and runs submitted tasks, returning a Future for each result, which avoids the cost of creating threads for every task. CompletableFuture lets you chain asynchronous steps.

34. What is the transient keyword?

A transient field is excluded when an object is serialized with Java’s built-in serialization. When the object is deserialized, that field gets its default value: null, 0 or false. It is used for fields that should not be saved, such as passwords, caches, or values that can be recalculated.

35. How is memory organized, and how does garbage collection work?

Each thread has its own stack, which holds method calls and local variables, including references. Objects live on the shared heap. Class metadata lives in Metaspace, outside the heap, since Java 8. The garbage collector finds objects no longer reachable from any live reference and reclaims their memory. Most collectors are generational, because most objects die young. Modern collectors include G1, the default, and low-pause collectors such as ZGC and Shenandoah.

36. What is a class loader?

Class loaders load class files into the JVM when they are first needed. The built-in ones, since Java 9, are:

  • Bootstrap class loader: loads the core platform classes, such as java.lang.
  • Platform class loader: loads other platform modules. It replaced the extension class loader of Java 8 and earlier.
  • Application (system) class loader: loads classes from your application’s classpath or module path.

They follow parent delegation: a class loader asks its parent first, so core classes cannot be replaced by application code.

Modern Java

Java interview questions and answers: Modern Java Features by Release
Modern Java Features by Release (quick reference)

37. What were the main features of Java 8?

  • Lambda expressions and functional interfaces, for passing behavior as values.
  • The Stream API, for processing collections declaratively.
  • Optional, to represent a value that may be absent.
  • Default and static methods in interfaces.
  • The java.time date and time API.
List<String> names = orders.stream()
    .filter(o -> o.total() > 1000)
    .map(Order::customerName)
    .distinct()
    .sorted()
    .toList();

38. Which Java versions are long-term support releases?

Java has a new release every six months, and every two years one is a long-term support (LTS) release, which vendors support for years. The LTS versions are Java 8, 11, 17, 21 and 25. Most companies run on an LTS version, so interviewers often ask which version you have used and what changed.

39. What are records, sealed classes and var?

  • var (Java 10): lets the compiler infer the type of a local variable, as in var list = new ArrayList<String>();. The variable is still statically typed.
  • Records (Java 16): concise, immutable data classes. record Point(int x, int y) {} generates the constructor, accessors, equals(), hashCode() and toString().
  • Sealed classes (Java 17): restrict which classes may extend or implement a type, with permits. Combined with pattern matching in switch (Java 21), the compiler can check that every case is handled.

40. What are virtual threads?

Virtual threads, final in Java 21, are lightweight threads managed by the JVM rather than the operating system. You can run millions of them, so a server can use a simple one-thread-per-request style without running out of threads. When a virtual thread blocks on I/O, the JVM parks it and frees the underlying platform thread for other work. They suit I/O-heavy applications such as web servers, not CPU-heavy computation.

try (var executor = Executors.newVirtualThreadPerTaskExecutor()) {
    for (var url : urls) {
        executor.submit(() -> fetch(url));
    }
}

Final tips for Java interview questions and answers

Most Java interviews come back to the same foundations: OOP, how strings and collections behave, exceptions, and how threads share data safely. Knowing what changed in modern Java, from lambdas and streams to records and virtual threads, shows you are current. If you were asked a Java question recently that is not here, share it in the comments and we can work through the answer together.

Sources and further reading

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *