Java interview questions for testers
Updated 2026-11-12 · 11 min read
Thirty-three Java questions an automation tester actually gets asked, each tied to how you use it in a framework: strings, collections, OOP, exceptions, streams, threads and the usual coding problems.
You are not interviewed as a Java developer. You are expected to know the part of Java that a test framework uses, and to explain it with an example from your own tests.
Core language
1. What is the difference between == and .equals()?
== compares references for objects (are they the very same object?) and values for primitives. .equals() compares content when the class overrides it, as String does.
String a = new String("qa");
String b = new String("qa");
System.out.println(a == b); // false: two objects
System.out.println(a.equals(b)); // true: same text
In tests: always compare text with equals, never ==. TestNG's assertEquals already does the right thing.
2. Why is String immutable and what does that mean for you?
Once created, a String cannot change; operations like concat or replace return a new string. This makes strings safe to share and cache. For repeated modification in a loop use StringBuilder, which changes in place and is faster.
Likely follow-up: String vs StringBuilder vs StringBuffer? StringBuffer is the old synchronised (thread-safe, slower) version. In test code StringBuilder is the usual choice.
3. Explain the four pillars of OOP with a test framework example.
Encapsulation: a page object keeps its locators private and exposes methods. Inheritance: a BaseTest class holds set-up and tear-down that all tests extend. Polymorphism: a WebDriver variable can hold a ChromeDriver or FirefoxDriver, and the same test code runs on both. Abstraction: WebDriver is an interface, so your test depends on what a driver can do, not how.
4. Interface vs abstract class?
An interface describes a capability and a class can implement many. An abstract class can hold state and shared code, and a class can extend only one. Use an interface for a contract (WebDriver, a ReportListener), an abstract class when subclasses share real code (a BasePage).
5. What do static, final and this mean?
static belongs to the class, not an object (a utility method such as Utils.randomEmail(), or a shared config). final means it cannot be reassigned (a constant), a method cannot be overridden, or a class cannot be extended. this refers to the current object, commonly to separate a field from a parameter of the same name.
6. Overloading vs overriding?
Overloading: same method name with different parameters in the same class, resolved at compile time (click(By) and click(WebElement)). Overriding: a subclass replaces a parent's method with the same signature, resolved at run time. That is how a ChromePage can customise a BasePage method.
Collections
7. ArrayList vs LinkedList, and List vs Set vs Map?
A List keeps order and allows duplicates (ArrayList is fast for reading by index and is the default choice). A Set holds no duplicates (HashSet for speed, LinkedHashSet to keep insertion order, TreeSet to keep it sorted). A Map stores key-value pairs with unique keys (HashMap). In tests: a List<WebElement> from findElements, a Set to remove duplicates from collected links, a Map<String,String> for test data rows.
8. How does a HashMap work, in brief?
It computes the key's hashCode() to choose a bucket, then uses equals() to find the right key inside the bucket. So keys that are used in a HashMap need consistent hashCode and equals. Allows one null key. Not thread-safe; use ConcurrentHashMap when threads share it.
9. Write code to remove duplicates from a list.
List<String> names = List.of("asha", "ravi", "asha", "meena", "ravi");
List<String> unique = new ArrayList<>(new LinkedHashSet<>(names)); // keeps first-seen order
System.out.println(unique); // [asha, ravi, meena]
10. Count the occurrences of each word in a sentence.
String text = "to be or not to be";
Map<String, Integer> count = new LinkedHashMap<>();
for (String w : text.split("\\s+")) {
count.merge(w, 1, Integer::sum);
}
System.out.println(count); // {to=2, be=2, or=1, not=1}
Exceptions
11. Checked vs unchecked exceptions?
Checked exceptions (IOException, SQLException) must be caught or declared, and the compiler enforces it. Unchecked ones (RuntimeException and subclasses such as NullPointerException, NoSuchElementException from Selenium) are not enforced. Selenium's exceptions are unchecked, so a failed lookup does not force a try block.
12. What is the difference between throw and throws, and what does finally do?
throw raises an exception now. throws in a method signature warns callers that it may raise one. finally runs whether or not an exception happened, which is where you release resources, such as driver.quit(). For anything AutoCloseable, prefer try-with-resources.
try (BufferedReader r = Files.newBufferedReader(Path.of("data.csv"))) {
System.out.println(r.readLine());
} // closed automatically
Coding problems you will be asked
13. Reverse a string without using a library method.
static String reverse(String s) {
char[] c = s.toCharArray();
for (int i = 0, j = c.length - 1; i < j; i++, j--) {
char t = c[i]; c[i] = c[j]; c[j] = t;
}
return new String(c);
}
14. Check whether a string is a palindrome.
static boolean isPalindrome(String s) {
String clean = s.toLowerCase().replaceAll("[^a-z0-9]", "");
int i = 0, j = clean.length() - 1;
while (i < j) if (clean.charAt(i++) != clean.charAt(j--)) return false;
return true;
}
// isPalindrome("A man, a plan, a canal: Panama") -> true
15. Check whether two strings are anagrams.
static boolean isAnagram(String a, String b) {
char[] x = a.replace(" ", "").toLowerCase().toCharArray();
char[] y = b.replace(" ", "").toLowerCase().toCharArray();
Arrays.sort(x); Arrays.sort(y);
return Arrays.equals(x, y);
}
16. Find the second largest number in an array.
static int secondLargest(int[] a) {
int first = Integer.MIN_VALUE, second = Integer.MIN_VALUE;
for (int n : a) {
if (n > first) { second = first; first = n; }
else if (n > second && n != first) second = n;
}
return second; // Integer.MIN_VALUE if there is none
}
State your edge cases aloud: array shorter than two elements, all equal values, negatives.
17. Find the first non-repeating character in a string.
static Character firstUnique(String s) {
Map<Character, Integer> freq = new LinkedHashMap<>();
for (char c : s.toCharArray()) freq.merge(c, 1, Integer::sum);
for (var e : freq.entrySet()) if (e.getValue() == 1) return e.getKey();
return null;
}
More core Java for test code
18. 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, a final class cannot be extended. finally is a block that runs after try and catch whether or not an exception happened (where driver.quit() belongs). finalize() was a method called by the garbage collector before an object was removed; it is deprecated and should not be used.
19. How do you create a custom exception, and why would a framework have one?
Extend RuntimeException (unchecked) or Exception (checked). A framework uses them to give failures a meaningful name and message, such as ElementNotReadyException("Checkout button not clickable after 10s"), instead of a raw stack trace from deep inside Selenium.
public class TestDataException extends RuntimeException {
public TestDataException(String message, Throwable cause) { super(message, cause); }
}
20. HashSet vs TreeSet vs LinkedHashSet?
HashSet: fastest, no order. LinkedHashSet: remembers insertion order. TreeSet: keeps elements sorted (and needs them to be comparable). Pick by what you need: unique values only, unique in the order found, or unique and sorted.
21. Comparable vs Comparator?
Comparable is the natural order built into a class (compareTo). Comparator is a separate rule you pass in, so you can sort the same objects in different ways.
List<String> names = new ArrayList<>(List.of("Ravi", "asha", "Meena"));
names.sort(String.CASE_INSENSITIVE_ORDER); // a Comparator
users.sort(Comparator.comparing(User::getAge).thenComparing(User::getName));
22. What are generics and why are they useful?
They let a class or method work with a type you choose, checked at compile time: List<String> can only hold strings, so you do not cast and a wrong type is a compile error, not a run-time crash. In a framework you see them in Map<String, String> for test data and in helper classes such as Page<T>.
23. What is a lambda and what is a stream? Give a tester's example.
A lambda is a short anonymous function. A stream processes a collection with a chain of steps (filter, map, collect). Example: collect the text of all visible items.
List<String> names = driver.findElements(By.cssSelector(".item")).stream()
.filter(WebElement::isDisplayed)
.map(WebElement::getText)
.map(String::trim)
.collect(Collectors.toList());
24. What is the difference between this and super?
this refers to the current object; use it to separate a field from a parameter of the same name or to call another constructor. super refers to the parent class; use it to call the parent's constructor or an overridden parent method. A BasePage constructor taking the driver is called by each page's constructor with super(driver).
25. What is a constructor, and can it be overridden?
A constructor initialises an object when it is created; it has the class name and no return type. Constructors are not inherited, so they cannot be overridden, but they can be overloaded (several with different parameters).
26. Is the Singleton pattern a good idea for the WebDriver?
Usually not. A singleton driver shared by the whole suite breaks parallel runs, because every thread would drive the same browser. A better pattern is a factory that creates one driver per test or per thread, stored in a ThreadLocal<WebDriver>. Singletons are fine for read-only things such as configuration.
27. How do you read test data from a file in a framework?
Use the format that suits the data: a .properties file or environment variables for settings, JSON or YAML for structured data, CSV or Excel for tables of inputs. Load it once into a small data class, never scatter file reading across tests, and never commit real credentials.
Properties p = new Properties();
try (InputStream in = Files.newInputStream(Path.of("config/test.properties"))) { p.load(in); }
String baseUrl = System.getProperty("baseUrl", p.getProperty("baseUrl"));
28. What is ThreadLocal and why does parallel testing need it?
It gives each thread its own copy of a variable. Parallel tests each need their own driver; if the driver lives in a plain static field, threads overwrite each other's browser. With ThreadLocal<WebDriver> each thread sees only its own.
29. How do you do multithreading basics in Java, and where does a tester meet it?
Mostly indirectly: TestNG or JUnit run tests on several threads for you. You meet threads when sharing data (use thread-safe collections such as ConcurrentHashMap), when sharing the driver (use ThreadLocal), and when writing a test that waits for background work (use a timeout and a condition, never a fixed Thread.sleep).
More coding questions
30. Count the vowels in a string.
static int vowels(String s) {
int n = 0;
for (char c : s.toLowerCase().toCharArray()) if ("aeiou".indexOf(c) >= 0) n++;
return n;
}
31. Print the first N Fibonacci numbers.
static void fibonacci(int n) {
long a = 0, b = 1;
for (int i = 0; i < n; i++) {
System.out.print(a + " ");
long next = a + b; a = b; b = next;
}
}
// fibonacci(8) prints 0 1 1 2 3 5 8 13
32. Check whether a number is prime.
static boolean isPrime(int n) {
if (n < 2) return false;
for (int i = 2; (long) i * i <= n; i++) if (n % i == 0) return false;
return true;
}
Say why the loop stops at the square root: if a number has a factor larger than its square root, it also has one smaller.
33. Swap two numbers without a third variable.
int a = 5, b = 9;
a = a + b; // 14
b = a - b; // 5
a = a - b; // 9
Mention that in real code you would use a temporary variable, and that this trick can overflow for very large values.
How to practise
Type these out, do not just read them. Run each with three inputs: a normal one, an empty one and an awkward one. Interviewers often ask "what would you test?" about your own function, and your answer is the same boundary thinking you use in manual testing.
Want a project you can show in interviews?
The portfolio project kit walks you through testing a deliberately buggy app with Selenium or Playwright and API tests, then explaining it. The app itself is free.
