How to Pass a Java Interview: Top Questions and Answers

Online Python Trainer for Beginners

Learn Python easily without overwhelming theory. Solve practical tasks with automatic checking, get hints in Russian, and write code directly in your browser — no installation required.

Start Course

How to Pass a Java Interview: Breaking Down Top Questions with Examples



A Java developer interview is not just a test of theory, but also a demonstration of practical thinking. Employers want to see that you haven't just memorized syntax, but understand how the virtual machine works, how collections are structured, and how to write thread-safe code. In this article, we have gathered key questions often asked in technical interviews and provided detailed answers with examples in Java.



1. Questions on Java Core and OOP Basics



Any interview starts with basic principles. The interviewer checks how deeply you understand the object-oriented programming paradigm and the structure of the language. Here are the top 3 questions from this category.



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

This is a classic. An abstract class can contain both abstract and regular methods with implementation, as well as fields and constructors. An interface (before Java 8) contained only method signatures. Starting with Java 8, default and static methods appeared in interfaces, and with Java 9 — private methods. The main difference: you can inherit from only one abstract class, but implement multiple interfaces.



// Abstract classabstract class Animal {    String name;    abstract void sound();    void sleep() { System.out.println("Zzz"); }}

// Interfaceinterface Flyable { void fly(); default void glide() { System.out.println("Gliding..."); }}

class Bird extends Animal implements Flyable { @Override void sound() { System.out.println("Chirp"); } @Override public void fly() { System.out.println("Flying"); }}


What is polymorphism? Give an example.

Polymorphism is the ability of an object to take many forms. In Java, it is implemented through inheritance and interfaces. The most common example is method overriding.



List<String> list = new ArrayList<>();// Reference of type List, but object is ArrayList.// The add() method will be called from the ArrayList implementation.list.add("Polymorphism example");


How does == differ from equals()?

== compares references (memory addresses), while equals() compares logical content. For wrapper classes (Integer, String), equals() is overridden and compares values. However, for Integer there is a cache from -128 to 127, so == can behave unexpectedly.



Integer a = 100;Integer b = 100;System.out.println(a == b); // true (both from cache)

Integer c = 200;Integer d = 200;System.out.println(c == d); // false (different objects)System.out.println(c.equals(d)); // true


2. Java Collections: Data Structures and Algorithms



Collections are the heart of any Java application. Without understanding them, it is impossible to pass even a Junior-level interview. Interviewers like to ask about operation complexity and internal structure.



How is HashMap structured? How does hashing work?

HashMap stores key-value pairs in an array of "buckets". When adding an element, the key's hash code is calculated, and the bucket number is determined based on it. If the bucket already has elements, a linked list or a tree is used (if there are more than 8 elements). In Java 8+, for optimization during collisions, the list is transformed into a red-black tree.



Map<String, Integer> map = new HashMap<>();map.put("Java", 1);map.put("Python", 2);// If "Java" and "Python" have the same hashCode — there will be a collision.System.out.println(map.get("Java")); // O(1) on average


What is the difference between ArrayList and LinkedList? When to use which?

ArrayList is based on a dynamic array. Access by index is O(1), insertion/deletion in the middle is O(n). LinkedList is based on a doubly linked list. Access by index is O(n), but insertion/deletion at the beginning or middle is O(1) (if you have a reference to the node). In practice, ArrayList is used much more often due to better cache locality and lower memory overhead.



List<String> arrayList = new ArrayList<>();arrayList.add("A"); // O(1) amortizedarrayList.get(0);   // O(1)

List<String> linkedList = new LinkedList<>();linkedList.add("B"); // O(1)linkedList.get(0); // O(n) — traversal from the beginning


3. Multithreading and Concurrency



Questions about threads are a mandatory part of an interview for a Middle+ level. The interviewer checks your understanding of the Java Memory Model, synchronization mechanisms, and the java.util.concurrent package.



What is the difference between synchronized and Lock?

synchronized is a built-in keyword that provides automatic acquisition and release of a monitor. Lock (from java.util.concurrent.locks) is a more flexible mechanism: it supports attempts to acquire a lock with a timeout, multiple condition variables, and fair locking. However, synchronized is simpler and less error-prone.



// Using synchronizedpublic synchronized void increment() { count++; }

// Using Lockprivate final Lock lock = new ReentrantLock();public void increment() { lock.lock(); try { count++; } finally { lock.unlock(); }}


What is volatile? When is it used?

The volatile keyword ensures that changes to a variable are immediately visible to all threads. It prevents caching the variable in the thread's local memory. However, volatile does not guarantee atomicity for compound operations like count++.



class Flag {    volatile boolean running = true;        void stop() { running = false; }    void work() {        while (running) {            // Thread will see the change immediately        }    }}


What is the difference between wait() and sleep()?

wait() is called on an object within a synchronized block and releases the monitor, allowing other threads to enter the synchronized block. sleep() is a static method of the Thread class that pauses the current thread without releasing locks. wait() requires notify()/notifyAll() to wake up, while sleep() wakes up after a specified time.



synchronized (lock) {    try {        lock.wait(); // Releases the monitor and waits        // Or Thread.sleep(1000); // Does not release the monitor    } catch (InterruptedException e) {        Thread.currentThread().interrupt();    }}


4. Java Memory Model and Garbage Collection



Understanding how memory is organized and how garbage collection works is important for writing high-performance applications. Interviewers often ask about the structure of the heap and the operation of collectors.



How is the Java heap structured?

The heap is divided into generations: Young Generation (Eden, S0, S1) and Old Generation. Objects are first created in Eden. After minor GC, surviving objects are moved to S0 or S1. After several cycles, objects are promoted to the Old Generation. There is also Metaspace (replacing PermGen), which stores class metadata.



// JVM parameters for heap configuration// -Xms256m - initial heap size// -Xmx1024m - maximum heap size// -XX:NewRatio=3 - ratio of Young to Old generation


How does Garbage Collection work? Name the types of collectors.

GC automatically removes objects that are no longer referenced. The main types of collectors: Serial (for single-threaded applications), Parallel (default in Java 8), CMS (minimizes pauses), G1 (default from Java 9, divides the heap into regions), and ZGC (for ultra-low latency). The choice depends on the application's requirements for throughput and pause time.



// Example of enabling G1// -XX:+UseG1GC// -XX:MaxGCPauseMillis=200


5. SQL and Databases



Even if you are applying for a pure Java position, knowledge of SQL is often required. Interviewers check the ability to write queries and understand indexing.



What is the difference between JOIN and subquery? When to use which?

JOIN combines rows from two tables based on a condition. A subquery is a query nested inside another query. JOINs are usually more efficient because the database optimizer can better plan the execution. Subqueries are convenient for aggregating data or checking existence.



-- JOIN exampleSELECT e.name, d.department_nameFROM employees eJOIN departments d ON e.department_id = d.id;

-- Subquery exampleSELECT nameFROM employeesWHERE department_id IN (SELECT id FROM departments WHERE location = 'New York');


How do indexes work? What types of indexes are there?

An index is a data structure (usually a B-tree) that speeds up data retrieval. The main types: B-tree index (for equality and range queries), Hash index (for equality only), Bitmap index (for columns with few unique values), and Full-text index (for text search). Indexes speed up SELECT but slow down INSERT/UPDATE/DELETE.



-- Creating an indexCREATE INDEX idx_employee_name ON employees(name);

-- Composite indexCREATE INDEX idx_dept_salary ON employees(department_id, salary);


Conclusion



Preparing for a Java interview is a systematic process. Don't just memorize answers — try to understand the underlying principles. Write code, experiment with different approaches, and analyze how the JVM works. The more practical experience you have, the more confident you will feel during the interview. Good luck!

Blogs

Book Recommendations