Interview Questions

40 Java Interview Questions for Automation Testers

Forty Java questions automation interviewers actually ask, with short model answers, Selenium examples and the coding programs you should be able to write from memory.

✍️ By QA Jobs India📅 13 Nov 2026⏱ 8 min read

In most Selenium with Java interviews, the Java round decides the outcome before anyone asks about locators. Interviewers know that a tester who understands collections, exceptions and OOP can learn any framework, while one who only memorised Selenium commands struggles the moment something breaks. That is why Java interview questions for testers focus on fundamentals applied to automation.

The 40 questions below are grouped into core Java, OOP, strings and collections, exceptions, and Java inside a Selenium framework, followed by three programs you should be able to write on a whiteboard. Answers are written to be spoken in under a minute. Examples assume Java 17, which most current frameworks use.

Key takeaways

  • Interviewers test Java through automation examples: WebDriver driver = new ChromeDriver() is an OOP question in disguise.
  • Collections and strings make up a large share of coding questions. Practise them until they feel routine.
  • Know the difference between checked and unchecked exceptions, and which Selenium exceptions you have handled.
  • Be ready to connect each OOP concept to where it appears in your framework.
  • Write the common programs by hand at least once; typing in an IDE with autocomplete is not the same.

Core Java interview questions for testers (1-10)

1. What is the difference between JDK, JRE and JVM?

The JVM runs Java bytecode. The JRE is the JVM plus the standard libraries needed to run programs. The JDK includes the JRE plus development tools like the compiler (javac). To write and compile tests you need the JDK.

2. Why is Java platform independent?

Java source compiles to bytecode, which runs on any operating system that has a JVM. The same test JAR can run on Windows, macOS or a Linux CI agent.

3. What are the primitive data types?

byte, short, int, long, float, double, char and boolean. Everything else, including String, is an object.

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

== compares references for objects (and values for primitives). equals() compares content when the class overrides it, as String does. Always compare page text with equals(), never ==.

5. What does the static keyword mean?

A static member belongs to the class, not to an instance. Utility methods like a config reader are often static. Avoid a static WebDriver field if you run tests in parallel, because all threads would share it.

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

final prevents reassignment, overriding or inheritance. finally is a block that runs after try/catch, useful for cleanup such as quitting the driver. finalize was a garbage collection hook; it is deprecated and should not be used.

7. What are wrapper classes and autoboxing?

Wrapper classes like Integer and Boolean wrap primitives so they can be used in collections. Autoboxing converts automatically, for example adding an int to a List<Integer>.

8. What is the difference between break and continue?

break exits the loop; continue skips to the next iteration. Example: stop scanning table rows once a match is found with break.

9. What does var do?

Since Java 10, var lets the compiler infer a local variable’s type: var rows = driver.findElements(By.tagName("tr"));. The type is still fixed at compile time.

10. What is a constructor? Can it be overridden?

A constructor initialises a new object and has the same name as the class with no return type. Constructors are not inherited, so they cannot be overridden, but they can be overloaded. Page classes usually take a WebDriver in their constructor.

OOP questions with Selenium examples (11-18)

11. What are the four pillars of OOP?

Encapsulation, inheritance, polymorphism and abstraction. Interviewers expect an example of each from your framework, so prepare those in advance.

12. Where do you use encapsulation in your framework?

Page classes keep locators private and expose public methods such as loginAs(). Tests cannot touch locators directly, which protects them from UI changes. Our Page Object Model guide shows this in code.

13. Where is inheritance used?

Page classes extend a BasePage that holds waits and helpers. Test classes extend a BaseTest that handles setup and teardown.

14. Explain WebDriver driver = new ChromeDriver();

WebDriver is an interface; ChromeDriver is a class that implements it through its parent classes. Declaring the variable as the interface type is upcasting, a form of runtime polymorphism. It lets you switch to FirefoxDriver without changing the rest of the code. The Selenium documentation uses the same pattern in its examples.

15. What is the difference between overloading and overriding?

Overloading means same method name with different parameters in the same class, resolved at compile time. Overriding means a subclass provides its own implementation of a parent method, resolved at runtime. Selenium’s WebDriverWait constructors are an example of overloading.

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

An abstract class can have state, constructors and both abstract and concrete methods; a class can extend only one. An interface defines a contract; since Java 8 it can have default and static methods, and a class can implement many. BasePage is often abstract; WebDriver is an interface.

17. What do this and super refer to?

this refers to the current object; super refers to the parent class. super(driver) in a page constructor calls the BasePage constructor.

18. What are access modifiers?

public (everywhere), protected (same package and subclasses), default or package-private (same package) and private (same class). Use protected for helpers in BasePage that subclasses need.

Strings and collections (19-28)

19. Why are strings immutable?

Once created, a String cannot change; operations return new strings. This makes strings safe to share and cache in the string pool.

20. String vs StringBuilder vs StringBuffer?

String is immutable. StringBuilder is mutable and fast, for building text in a loop. StringBuffer is mutable and synchronised, so slower; it is rarely needed in test code.

21. Which string methods do you use most in automation?

trim(), contains(), equalsIgnoreCase(), replace(), split(), substring() and isBlank(). A common case is cleaning “Rs. 1,299” into a number with replaceAll("[^0-9]", "").

22. What is the difference between List, Set and Map?

List is ordered and allows duplicates. Set has no duplicates. Map stores key-value pairs with unique keys.

23. Where do collections appear in Selenium?

findElements() returns List<WebElement>. getWindowHandles() returns Set<String>. Test data from a properties file or JSON often ends up in a Map<String, String>.

24. ArrayList vs LinkedList?

ArrayList is backed by an array and offers fast random access. LinkedList is faster for frequent insertions and removals in the middle. In test code, ArrayList is the usual default.

25. HashSet vs LinkedHashSet vs TreeSet?

HashSet has no guaranteed order. LinkedHashSet keeps insertion order. TreeSet keeps elements sorted. To check that a dropdown has unique options in order, LinkedHashSet is handy.

26. HashMap vs Hashtable?

HashMap is not synchronised and allows one null key and null values. Hashtable is synchronised and allows no nulls. For thread-safe maps, ConcurrentHashMap is the modern choice.

27. How do you iterate over a Map?

Map<String, Integer> stock = Map.of("pen", 10, "book", 4);
for (Map.Entry<String, Integer> entry : stock.entrySet()) {
    System.out.println(entry.getKey() + " = " + entry.getValue());
}

28. How do you use streams on a list of elements?

List<String> prices = driver.findElements(By.cssSelector(".price"))
        .stream()
        .map(WebElement::getText)
        .filter(text -> !text.isBlank())
        .toList();

Stream.toList() is available from Java 16.

Exceptions (29-33)

29. Checked vs unchecked exceptions?

Checked exceptions, like IOException, must be caught or declared. Unchecked exceptions extend RuntimeException and need not be declared. Most Selenium exceptions are unchecked.

30. Which Selenium exceptions have you handled?

NoSuchElementException, StaleElementReferenceException, TimeoutException, ElementClickInterceptedException and NoSuchFrameException. For each, explain the cause and your fix, for example re-locating an element after a page refresh to avoid a stale reference.

31. What is the difference between throw and throws?

throw raises an exception inside a method. throws in a method signature declares exceptions the method may pass to its caller.

32. What is try-with-resources?

It closes resources automatically when the block ends:

try (FileInputStream in = new FileInputStream("config.properties")) {
    Properties props = new Properties();
    props.load(in);
    System.out.println(props.getProperty("baseUrl"));
}

The enclosing method must handle or declare IOException.

33. Should you catch exceptions in test methods?

Usually not. Letting the exception fail the test gives a clear report. Catch only when you have a specific recovery or want to add context and rethrow.

Java inside a Selenium framework (34-40)

34. How do you read configuration?

With Properties for simple key-value files, or a JSON or YAML library for structured data. Keep environment URLs and browser names in config, not in tests.

35. How do you make the driver thread-safe for parallel runs?

Store it in a ThreadLocal<WebDriver> so each thread gets its own instance, and call remove() after quitting. Our TestNG tutorial explains the parallel settings that need this.

36. What is the Singleton pattern and is it useful in tests?

A Singleton ensures one instance of a class. It suits a config reader. It is a poor fit for the driver in parallel runs, unless combined with ThreadLocal.

37. How do you generate random test data?

Use java.util.UUID.randomUUID() for unique ids, or ThreadLocalRandom.current().nextInt(1000, 9999) for numbers. Unique data prevents tests from colliding on shared environments.

38. How do you handle dates?

Use java.time: LocalDate.now().plusDays(7).format(DateTimeFormatter.ofPattern("dd/MM/yyyy")) for a date one week ahead in Indian format. Avoid the old Date and SimpleDateFormat classes.

39. What is an enum and where would you use it?

An enum is a fixed set of constants, such as enum Browser { CHROME, FIREFOX, EDGE }. It prevents typos in browser names and makes switch statements safer.

40. What Java features from recent versions have you used?

Good answers include var, text blocks for JSON payloads, records for simple test data objects, Stream.toList() and the java.time API. Use only what you have actually used, because follow-up questions are likely.

Three programs to practise by hand

ProgramConcept tested
Reverse a stringLoops, StringBuilder
Count character occurrencesHashMap, char handling
Find duplicates in an arrayHashSet
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Set;

public class Programs {

    static String reverse(String input) {
        StringBuilder sb = new StringBuilder();
        for (int i = input.length() - 1; i >= 0; i--) {
            sb.append(input.charAt(i));
        }
        return sb.toString();
    }

    static Map<Character, Integer> countChars(String input) {
        Map<Character, Integer> counts = new LinkedHashMap<>();
        for (char c : input.toCharArray()) {
            counts.merge(c, 1, Integer::sum);
        }
        return counts;
    }

    static Set<Integer> duplicates(int[] numbers) {
        Set<Integer> seen = new HashSet<>();
        Set<Integer> dupes = new HashSet<>();
        for (int n : numbers) {
            if (!seen.add(n)) {
                dupes.add(n);
            }
        }
        return dupes;
    }

    public static void main(String[] args) {
        System.out.println(reverse("selenium"));
        System.out.println(countChars("testing"));
        System.out.println(duplicates(new int[] {3, 7, 3, 9, 7, 1}));
    }
}

Interviewers often ask you to do the reverse without StringBuilder.reverse(), which is why the loop version is shown. These three programs appear in so many sets of Java interview questions for testers that it is worth being able to write them without an IDE.

🚀 Looking for Java automation testing jobs?

QA Jobs India shares 100+ fresh QA & software testing openings every morning — manual, automation, API and remote roles.

See today’s QA jobs →

FAQs

How much Java is required for automation testing?

You need core Java: OOP, strings, collections, exceptions, file handling and basic Java 8+ features like streams and lambdas. Advanced topics like multithreading internals are rarely needed beyond ThreadLocal for parallel runs.

Are Java coding questions asked for automation tester roles?

Yes. Most automation interviews include a few programs on strings, arrays and collections. Product companies and SDET roles may also ask easy to medium data structure problems.

Which Java version should testers learn?

Java 17 or 21, both long-term support releases. Most frameworks and tools support them, and the features you learn carry forward.

How do I prepare for Java questions as a manual tester moving to automation?

Learn Java alongside Selenium, not separately. Write small programs, then use the same concepts in a framework. A daily practice of one program plus one framework change works well.

Conclusion

Pick ten questions from this list that you could not answer confidently, write the code or explanation for each in your own repository, and say the answers aloud. Then move on to tool-specific practice with our Selenium interview questions and a structured QA interview preparation plan.

SIGN UP ONCE
Once you sign up, you get all this
Sign up now
  • 100+ fresh QA jobs daily + Direct HR email IDsLive every morning at 9 AM — apply straight to HR
  • Weekly Mega Job Fair800+ QA jobs from India & around the world, every week
  • Certified QA coursesUp to 3 courses included · all 17 for ₹500
  • AI ATS Resume BuilderFree resume points included
  • Full LinkedQA feedEvery post, fully unblurred
  • Complete QA Material libraryInterview Q&A, cheat sheets, templates & roadmaps

Instant activation right after payment · One login for jobs, courses, resume & LinkedQA

💎 Get every QA opening, every day

Join QA Jobs India Premium for 100+ verified QA jobs daily with HR contact details.

✓ You're subscribed — job alerts arrive daily at 9 AM
Scroll to Top