QA Interview Hub · Knowledge base · Quizzes · Українська
16 Java Core questions that come up in QA interviews, with short answers. Open the topic in the knowledge base for a deeper explanation.
For objects == compares references and equals compares content (if the class overrides it). I compare strings with equals or an assertion library, and with Objects.equals when null is possible. Integer wrappers are cached for −128…127, so == works for small numbers and breaks for large ones. Unboxing null throws NullPointerException. For money, BigDecimal from a string and compareTo, because equals treats 2.0 and 2.00 as different.
record (Java 16) — an immutable data carrier with a constructor, accessors and equals/hashCode/toString; enum — a fixed set of browsers, environments and roles, checked by the compiler; var (Java 10) — the local variable type is inferred; text blocks (Java 15) — multi-line JSON or SQL in triple quotes; pattern matching for instanceof. The reference is the current LTS (Java 25).
Encapsulation: a Page Object hides locators in private fields and exposes methods like login(user, password). Inheritance: shared behavior lives in a base class such as BasePage or BaseTest, and subclasses inherit it. Polymorphism: the code works with the WebDriver interface, and underneath it can be ChromeDriver or FirefoxDriver, so the test does not depend on the browser. Abstraction: the test calls checkoutPage.pay(card) and does not know which clicks and waits are hidden inside. I use inheritance carefully and often prefer composition, because deep hierarchies are hard to maintain.
Inheritance is "is a kind of": BaseTest for shared setup, BasePage for shared helpers; the base must be thin because Java has one parent and deep chains are brittle. Composition is "has": a page holds HeaderComponent or Table as a field and delegates. Interchangeable implementations (DriverFactory, TestDataProvider) I describe with an interface. Locators are private, actions public, and the test asserts, not the page.
A static field exists once per JVM and is shared by all threads: tests overwrite each other's driver, close a foreign browser, failures are flaky. The fix: an instance field (when the runner creates an instance per test) or ThreadLocal<WebDriver> with remove() after the test. The same applies to static state: the current user, a token, counters. Only stateless static utilities are safe.
List is an ordered collection with access by index that allows duplicates (ArrayList). Set stores only unique elements: HashSet with no guaranteed order, LinkedHashSet in insertion order, TreeSet sorted. Map holds "key — value" pairs with unique keys (HashMap, LinkedHashMap, TreeMap). In tests I use a List for table rows or elements on a page, a Set to find duplicates (compare the size of the list and of the set), and a Map for test data by key. Uniqueness of HashSet elements and HashMap keys depends on correct equals and hashCode, while TreeSet and TreeMap compare with compareTo or a Comparator.
If a.equals(b), then a.hashCode() == b.hashCode(); the reverse is not required. HashMap and HashSet pick a bucket by the hash and then compare with equals, so with equals alone contains() may not find the element. I override both together or take a record. I do not use objects as map keys if the fields used in their hash can change.
ObjectMapper.readValue turns JSON into a POJO or record and writeValue does the reverse; for List<User> a TypeReference is needed. In Jackson 2.x an unknown field throws UnrecognizedPropertyException by default: I add the field to the POJO or use @JsonIgnoreProperties(ignoreUnknown = true); Jackson 3 turns this check off by default. @JsonProperty maps a different field name; in Jackson 2.x LocalDate needs jackson-datatype-jsr310, while Jackson 3 has java.time support built in. I create one ObjectMapper and reuse it, and read files from the classpath (src/test/resources).
The compiler requires checked ones (IOException, SQLException) to be handled or declared; unchecked ones are RuntimeException subclasses (NullPointerException, IllegalArgumentException). AssertionError belongs to Error. For custom exceptions in test code I use unchecked and always pass the cause. I do not write an empty catch or only printStackTrace, do not catch Throwable around assertions (it swallows AssertionError) and do not write throws Exception everywhere. An expected exception I check with assertThrows or assertThatThrownBy.
An automatic close() call for AutoCloseable objects (streams, database connections, clients) after the block, on success and on exception. Closing is in reverse order of opening; an exception from close() is attached to the main one as suppressed and does not overwrite it. It replaces clumsy try/finally and prevents resource leaks in tests.
Stream: a source → lazy intermediate operations (filter, map, sorted) → a terminal one (toList, collect, count, anyMatch) that triggers the computation; a stream is used once; I avoid parallelStream in tests with shared state. Optional is "a value may be absent": orElseThrow with a message, orElseGet instead of orElse for costly values (orElse is always evaluated), get() without a check throws NoSuchElementException. I do not make Optional a field or parameter.
Each thread gets its own driver: an instance field if the runner creates an instance per test, or ThreadLocal<WebDriver> with set in setup and quit() and remove() in teardown (pool threads are reused). ThreadLocal is not inherited by child threads and does not make the driver itself thread-safe. In addition, data is unique for each test rather than a shared account.
given() — preconditions (baseUri, headers, a POJO body, authorisation), when() — the action (post("/users")), then() — checks (statusCode, header, body with Hamcrest matchers). extract().as(User.class) deserialises the response into a POJO (Jackson or Gson is needed), extract().path("id") takes one value. Shared parts go into a RequestSpecification, log().ifValidationFails() shows the request only on failure, and the schema is checked by json-schema-validator.
A builder sets valid defaults and the test changes only the needed field: aUser().withRole(ADMIN).build(); I generate unique values (email, login) inside for parallel tests. Lombok generates code at compile time: @Getter/@Setter, @Builder, @Value, @Slf4j. It works as an annotation processor (since JDK 23 it must be declared explicitly in the compiler), and @Data on mutable classes generates equals/hashCode over all fields. For simple data, a record.
Surefire runs unit tests in the test phase (*Test, Test*), Failsafe runs integration ones (*IT) in integration-test and verify checks the result, so environment shutdown runs even after a failure; I run mvn verify. Filters: -Dtest=LoginTest or LoginTest#validLogin, -Dgroups=smoke and -DexcludedGroups=slow (JUnit 5 tags, TestNG groups), the profile -Pstaging. -DskipTests compiles tests but does not run them, -Dmaven.test.skip=true does not compile.
Configuration in layers: defaults in .properties → overrides with -Dbrowser=firefox (System.getProperty with a default) → secrets from environment variables (System.getenv), not from the repository and not into the log. Logging through the SLF4J facade and one implementation (Logback): log.info("Order {} created", id) with placeholders, the exception as the last argument, no System.out and no passwords. Gradle: useJUnitPlatform(), gradlew test --tests; always the wrapper (mvnw, gradlew).