Java Interview Questions for Testers

These are the Java questions automation testers and SDETs are asked most — the core 20, plus five bonus questions that come up constantly in Selenium interviews. Each answer is short enough to say out loud, with a Selenium example where it helps. The code was compiled and run; the outputs are real. For the full learning path, start with The Complete Java for Testers Guide.

Advertisement

Java Basics & JVM (Q1–5)

Q1. Why is Java platform independent?

The compiler turns source code into bytecode (.class files), not machine code. Each operating system has its own JVM that runs the same bytecode — "write once, run anywhere". The JVM is platform-specific; the bytecode isn't.

Learn more: JVM & Execution

Q2. What happens inside the JVM?

The class loader loads classes, the bytecode verifier checks them, and the execution engine runs them — interpreting bytecode and compiling hot code to native code with the JIT compiler. Memory is split into the heap (objects) and stacks (method calls and local variables), and the garbage collector frees unused objects. JDK = JRE + development tools; JRE = JVM + libraries.

Q3. Where does execution begin?

At public static void main(String[] args). In a TestNG project you don't write main() — TestNG's own runner has it and calls your annotated methods.

Q4. Can code run before main()?

Yes — static blocks run when the class is loaded:

public class JavaQs {
    static {
        System.out.println("static block runs first");
    }

    public static void main(String[] args) {
        System.out.println("main starts");
    }
}
// Output: static block runs first → main starts

Frameworks use static blocks to load configuration once, for example in a ConfigReader.

Q5. while vs do-while?

while checks the condition first and may run zero times; do-while runs the body at least once, then checks.

int i = 10;

while (i < 5) {
    …
}                  // never runs

do {
    …
} while (i < 5);              // runs once

// Output: "do-while body runs once even though 10 < 5 is false"

OOP & Keywords (Q6–9)

Q6. What are Java's access modifiers?

Modifier Same class Same package Subclass (other package) Everywhere
private ✅ ❌ ❌ ❌
default (none) ✅ ✅ ❌ ❌
protected ✅ ✅ ✅ ❌
public ✅ ✅ ✅ ✅

In a framework: locators are private in page objects, the driver is protected in BaseTest, page methods are public.

Learn more: OOP & Keywords

Q7. When is super used?

To call the parent's constructor (super(driver) — it must be the first line), a parent method that's been overridden (super.open()), or a hidden parent field. Typical use: a page class passing the driver to BasePage.

Q8. Can an overriding method change the return type?

Only to a subtype — a covariant return type. Returning an unrelated type is a compile error; and two methods with the same parameters but different return types can't exist in one class either (that isn't valid overloading).

class Page {
    Page open() {
        return this;
    }
}

class LoginPage extends Page {
    @Override
    LoginPage open() {
        return this;
    }   // allowed: LoginPage is a Page
}

// new LoginPage().open() → LoginPage

This is what lets page-object methods chain fluently.

Q9. Is the default constructor still available after you write a constructor?

No. Java only generates the no-argument constructor when a class has none. Once you write LoginPage(WebDriver driver), new LoginPage() won't compile unless you add a no-arg constructor yourself.

Interfaces (Q10–12)

Q10. Can an interface be instantiated?

No — but an interface reference can point to an implementing object. That's Selenium's most famous line:

WebDriver driver = new ChromeDriver();

It lets the same test code run on any browser.

Learn more: Interfaces

Q11. What are default methods?

Methods with a body inside an interface (Java 8+), so interfaces can gain new behavior without breaking existing implementations:

interface Reporter {
    void log(String msg);

    default void info(String msg) {
        log("[INFO] " + msg);
    }
}

Reporter r = System.out::println;
r.info("default method from interface");
// [INFO] default method from interface

Q12. Can an interface be final?

No. final prevents extending or implementing, which would make an interface useless — the compiler rejects it.

Collections (Q13–16)

Q13. List vs Set vs Map?

List — ordered, duplicates allowed (findElements() returns one).

Set — unique values (getWindowHandles() returns one).

Map — key–value pairs with unique keys (configuration, test data).

Learn more: List vs Set vs Map

Q14. How does HashMap work internally?

put(key, value) calls key.hashCode(), maps the hash to a bucket, and stores the entry there. Different keys landing in the same bucket (a collision) are chained; since Java 8, a long chain becomes a balanced tree. get(key) finds the bucket from the hash, then uses equals() to find the exact key. It allows one null key, and when it gets about 75% full (the default load factor), it resizes.

That's why keys must implement equals() and hashCode() consistently — a lookup with an equal key then works:

map.put(new Key("k1"), "first");

map.get(new Key("k1"));
// "first" — because Key overrides both equals() and hashCode()

Q15. ArrayList vs LinkedList?

  ArrayList LinkedList
Structure Resizable array Doubly linked list
get(index) Fast — O(1) Slow — O(n)
Insert/remove in the middle Slower — elements shift Fast once you're at the node
Memory Less More (links per node)
Typical choice The default Queues and frequent add/remove at the ends

Q16. Collections.synchronizedMap() vs ConcurrentHashMap?

synchronizedMap() wraps a map with one lock for every operation — simple but slow under contention, and you must lock manually while iterating. ConcurrentHashMap allows concurrent reads and fine-grained writes, and its iterators don't throw ConcurrentModificationException. It doesn't allow null keys or values (verified: put(null, 1) throws a NullPointerException). In parallel test runs, ConcurrentHashMap is the usual choice for shared data such as report entries per thread.

Learn more: Collections

Strings & Exceptions (Q17–19)

Q17. String vs StringBuilder vs StringBuffer?

  String StringBuilder StringBuffer
Mutable No Yes Yes
Thread-safe Yes (immutable) No Yes (synchronized)
Speed Slow for repeated changes Fastest Slower than StringBuilder
new StringBuilder("Sel").append("enium").reverse();
// "muineleS"

Use StringBuilder for building strings in a loop; StringBuffer only when several threads really modify the same object.

Q18. How does exception handling work?

try wraps risky code, catch handles specific exceptions, finally always runs (cleanup), throw raises an exception and throws declares one. Checked exceptions (IOException, SQLException) must be caught or declared; unchecked ones (RuntimeException subclasses such as NullPointerException, and every Selenium exception) don't. Prefer try-with-resources for files and connections.

try {
    Integer.parseInt("abc");
}
catch (NumberFormatException e) {
    …
}
finally {
    …
}

Learn more: Strings, Wrappers & Exceptions

Q19. ClassNotFoundException vs NoClassDefFoundError?

ClassNotFoundException is a checked exception thrown when code loads a class by name at runtime (Class.forName("…")) and it isn't on the classpath. NoClassDefFoundError is an error thrown when a class that was present at compile time is missing or failed to initialize at runtime — often a missing or conflicting JAR.

Full comparison: ClassNotFoundException vs NoClassDefFoundError

JDBC (Q20)

Q20. What is JDBC, and what are the steps?

Java Database Connectivity — the standard API for querying databases from Java. Testers use it to verify that a UI or API action saved the right data.

String sql = "SELECT status FROM orders WHERE order_id = ?";

try (
    Connection con = DriverManager.getConnection(
        url,
        user,
        System.getenv("DB_PASSWORD")
    );
    PreparedStatement ps = con.prepareStatement(sql)
) {
    ps.setInt(1, 12345);

    try (ResultSet rs = ps.executeQuery()) {
        Assert.assertTrue(rs.next(), "order not found");
        Assert.assertEquals(rs.getString("status"), "PAID");
    }
}

Steps: add the database driver dependency → open a Connection → create a PreparedStatement (parameters prevent SQL injection) → execute → read the ResultSet → close everything (try-with-resources does it). Modern drivers register themselves, so Class.forName() is no longer needed.

Learn more: JDBC & Database Connectivity

Bonus: Five More You'll Be Asked (Q21–25)

Q21. == vs equals()?

== compares references (same object?); equals() compares content. For String a = "test" and b = new String("test"): a == b is false, a.equals(b) is true. Always compare getText() results with equals().

Q22. Why must equals() and hashCode() be overridden together?

Equal objects must have equal hash codes. If you override only equals(), a HashMap or HashSet looks in the wrong bucket and treats equal objects as different.

Q23. What does static mean?

It belongs to the class, not to objects — one shared copy. Good for constants and utilities; dangerous for a static WebDriver, which every parallel thread would share. Use ThreadLocal instead — see Parallel Execution.

Q24. final vs finally vs finalize?

final prevents reassignment, overriding or inheritance; finally always runs after try/catch; finalize() is deprecated — don't use it.

More: Java for Selenium.

Q25. Why does removing items in a for-each loop fail?

for (Integer x : list)
    if (x == 2)
        list.remove(x);   // ConcurrentModificationException

list.removeIf(x -> x == 2);   // ✅ [1, 3, 4]

The for-each loop's iterator detects the list changed underneath it. Use removeIf() or an explicit Iterator.remove().

Practice these under time pressure in the Java Interview Simulator, and step through the code examples in the Java Code Visualizer.

From the Interview Room

Java has been the language of every automation framework I've worked with — Selenium, TestNG, POM classes and Apache POI for Excel data. Interviews for automation roles regularly include basic programs like this one, often followed by a question on OOP concepts. Practice writing it by hand and explaining how you'd test it. On Canolog, the many forms and screens across sales, inventory, finance and service are where keeping page details in POM classes and reusable steps in a business library paid off. Link each Java answer to where it appears in a test framework.

📚 Official documentation: dev.java: Learn Java (Oracle) · Java 21 API documentation

FAQs

How much Java does an automation tester need?

OOP, collections, strings, exceptions and basic JDBC — plus the ability to write common coding programs and explain where these concepts appear in your framework.

Which Java topics are asked most in SDET interviews?

OOP in your framework, List/Set/Map, HashMap internals, String vs StringBuilder, exceptions, == vs equals, and static vs ThreadLocal for parallel runs.

Do testers get Java coding questions?

Almost always — reverse a string, find duplicates, second largest and similar. See the Java Coding Programs Cheat Sheet.

Should I learn Java 8 features?

Yes — lambdas, streams, default methods and Optional appear in modern frameworks and interviews.

How should I answer Java theory questions?

Give the definition in one sentence, then connect it to your framework — for example "WebDriver is an interface, so my tests run on any browser".

Next Steps