25 Java & Selenium Interview Questions Collections, Exceptions, Waits, Handlers

Java & Selenium Interview Prep: Collections, Exceptions, Waits, Handlers

Java & Selenium Deep Dive: Collections, Exceptions, Waits, Handlers

Real interview concepts with framework examples – No fluff, only clarity

Java Collections Framework

1. Difference between List, Set, and Map

List, Set, and Map are core interfaces of the Java Collection Framework. A List stores elements in an ordered sequence and allows duplicates (e.g., ArrayList, LinkedList). Useful when order matters or when you need indexed access.

A Set stores unique elements only – no duplicates. It uses hashing or natural ordering (HashSet, TreeSet). Ideal for maintaining distinct values, like unique validation errors.

A Map stores key-value pairs, with unique keys. Each key maps to exactly one value (HashMap, TreeMap). In automation, maps are often used for configuration (key = property name, value = property value) or test data sets.

In Selenium, List is frequently used to handle collections of WebElements. Set can eliminate duplicate window handles. Map stores environment configs (URL, browser, timeout).

2. Difference between Array and ArrayList

ArrayArrayList
Fixed size – length defined at creationDynamic size – grows/shrinks automatically
Part of core Java (not Collection)Part of java.util.Collection
Can hold primitives and objectsOnly objects (uses wrapper classes for primitives)
No built-in methods; length fieldRich API: add(), remove(), contains(), etc.

ArrayList is generally preferred in automation because of its flexibility and convenient methods.

3. Difference between HashMap and HashTable

  • Synchronization: HashMap is not synchronized → faster, suited for single-thread. HashTable is synchronized → thread-safe but slower.
  • Null handling: HashMap allows one null key and multiple null values. HashTable does not permit null keys or values.
  • Legacy: HashTable is a legacy class; HashMap is part of modern Collections and preferred.

In frameworks, HashMap is widely used for test data maps and configuration.

4. How HashMap works internally

HashMap stores entries in an array of buckets (Node<K,V>[] table). When put(key, value) is called:

  1. hashCode() of the key is computed.
  2. Hash is transformed to bucket index (index = hash & (n-1)).
  3. If bucket is empty, a new Node is placed there.
  4. If collision occurs (same index for different keys), a linked list or tree (since Java 8) stores multiple entries in same bucket.
  5. When get(key) is called, hashCode finds bucket, then equals() compares keys to locate correct value.

This gives O(1) average time for put/get.

5. Why Set does not allow duplicates?

A Set internally uses a Map (e.g., HashSet uses HashMap). Each element is stored as a key in the underlying map with a constant dummy value. Since Map keys must be unique, Set automatically discards duplicate elements. Before insertion, hashCode() and equals() verify whether the element already exists.

6. When did you use Map in your automation framework?

In automation frameworks, Map is commonly used for:

  • Configuration data: HashMap stores key-value pairs like browser=chrome, url=https://example.com, timeout=30.
  • Test data: Storing user credentials (username:password) or form field values.
  • JSON/response parsing: Converting API responses into Map for easy validation.
Map<String, String> config = new HashMap<>();
config.put("browser", "chrome");
config.put("headless", "true");
String browser = config.get("browser");

Exception Handling in Java

7. Difference between Checked and Unchecked Exception

Checked exceptions are verified at compile-time. The compiler forces you to handle them using try-catch or declare with throws. Examples: IOException, SQLException.

Unchecked exceptions occur at runtime and are not checked during compilation. They extend RuntimeException. Examples: NullPointerException, ArithmeticException, ArrayIndexOutOfBoundsException. They usually result from programming errors.

8. What is try-catch-finally?

try block encloses risky code. If exception occurs, control passes to catch block for handling. The finally block always executes (whether exception handled or not) – ideal for cleanup: closing browser, DB connection, file streams.

try {
    driver.findElement(By.id("username")).sendKeys("test");
} catch (NoSuchElementException e) {
    System.out.println("Element not found");
} finally {
    driver.quit();   // always executed
}

9. Have you created custom exceptions?

Yes, custom exceptions are created by extending Exception (checked) or RuntimeException (unchecked). In automation, I created InvalidBrowserException to handle unsupported browser names from config files.

class InvalidBrowserException extends Exception {
    public InvalidBrowserException(String msg) { super(msg); }
}

Usage: throw new InvalidBrowserException("Browser not supported: safari"); → improves readability and framework robustness.

10. What happens if an exception occurs in the finally block?

If an exception is thrown inside finally, it may suppress any unhandled exception from try or catch. This can lead to unexpected behavior. Therefore, keep finally simple — only cleanup operations that don't throw, or handle exceptions inside finally.

Selenium Waits & Synchronization

11. What is Wait in Selenium?

Wait in Selenium handles timing issues between script execution and application rendering. It pauses the script until an element is present, visible, clickable, or a condition met. This avoids NoSuchElementException and makes tests stable.

12. Difference between Implicit, Explicit, and Fluent Wait

  • Implicit Wait: Global setting applied to all element searches. Tells WebDriver to poll DOM for a given time if element not immediately present. driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
  • Explicit Wait: Waits for a specific condition on a particular element. Uses WebDriverWait with ExpectedConditions. WebDriverWait wait = new WebDriverWait(driver, 10); wait.until(ExpectedConditions.visibilityOf(element));
  • Fluent Wait: Advanced explicit wait with polling interval and exception ignoring. Wait wait = new FluentWait(driver).withTimeout(30, SECONDS).pollingEvery(5, SECONDS).ignoring(NoSuchElementException.class);

13. Which wait do you prefer and why?

Explicit Wait is preferred because it targets specific elements/conditions, avoids unnecessary waiting, and improves script efficiency. Implicit wait can slow down tests if applied globally. In most frameworks, explicit wait is the standard for dynamic elements.

14. What if implicit and explicit waits are used together?

Using both can cause unpredictable total wait times because implicit wait applies to element location, and explicit adds extra condition waits. It may double the waiting period. Best practice: avoid mixing; stick to explicit waits exclusively.

Element Handlers & Common Selenium Operations

15. How do you handle ElementNotInteractableException?

This exception occurs when element is present but not clickable/typeable (hidden, disabled, covered). Solutions:

  • Use explicit wait to ensure visibility/clickability.
  • Scroll element into view with JavaScriptExecutor.
  • Check if any overlay/popup is blocking and close it.
WebElement ele = driver.findElement(By.id("btn"));
((JavascriptExecutor) driver).executeScript("arguments[0].scrollIntoView(true);", ele);
wait.until(ExpectedConditions.elementToBeClickable(ele)).click();

16. How do you handle Dropdowns?

Using Select class for <select> tags.

WebElement dropdownElem = driver.findElement(By.id("month"));
Select select = new Select(dropdownElem);
select.selectByVisibleText("March");   // by visible text
select.selectByValue("3");              // by value attribute
select.selectByIndex(2);                // by index

17. How do you handle Alerts?

Switch to alert using driver.switchTo().alert().

Alert alert = driver.switchTo().alert();
String text = alert.getText();
alert.accept();      // click OK
// alert.dismiss();  // cancel

18. How do you handle Frames?

Switch to frame by index, name, or WebElement. After interaction, return to main content.

driver.switchTo().frame("frameName");   // or id or index
// interact inside frame
driver.switchTo().defaultContent();      // go back

19 & 20. How do you handle / switch between Multiple Windows?

Use window handles.

String parent = driver.getWindowHandle();
Set<String> allWindows = driver.getWindowHandles();
for (String win : allWindows) {
    if (!win.equals(parent)) {
        driver.switchTo().window(win);
        // perform actions in child window
        driver.close();
    }
}
driver.switchTo().window(parent);

21. How do you upload Files?

If input type="file", use sendKeys() with absolute file path.

driver.findElement(By.id("file-upload")).sendKeys("C:\\testdata\\image.png");

Avoid robot class unless necessary.

22. How do you handle Calendar / Date Picker?

Two approaches:

  • If input field is writable: driver.findElement(By.id("date")).sendKeys("25-03-2026");
  • If custom calendar: click to open, then iterate months/days to select desired date.

23. How do you perform Mouse Hover?

Using Actions class.

Actions actions = new Actions(driver);
WebElement menu = driver.findElement(By.id("main-menu"));
actions.moveToElement(menu).perform();

24. JavaScriptExecutor – when and why?

Used when Selenium fails to interact with element (hidden, disabled, or need to scroll). Also for retrieving page details. Example click:

JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("arguments[0].click();", element);

25. How do you scroll a page?

Using JavaScriptExecutor.

// scroll to bottom
js.executeScript("window.scrollTo(0, document.body.scrollHeight)");
// scroll to element
js.executeScript("arguments[0].scrollIntoView(true);", element);

Comments

Popular posts from this blog

What is Software Testing? Complete Beginner-Friendly Guide

Defect Management: Complete Guide with Tools & Best Practices

SDLC Models: Complete Guide with Advantages & Disadvantages