Home / Blog / 60 Selenium Interview Questions for Java Developers

Interview Prep

60 Selenium Interview Questions for Java Developers

QA Knowledge Hub·2026-04-14·11 min read

These 60 questions cover every area of Selenium + Java that interviewers test — from basics to framework architecture. Each answer is written at the level of a mid-level SDET.

WebDriver Basics

1. What is Selenium WebDriver?

Selenium WebDriver is an API and protocol that enables programmatic control of web browsers. It provides language bindings (Java, Python, C#, etc.) that send commands to browser-specific drivers (ChromeDriver, GeckoDriver) which translate them into browser actions. WebDriver is part of the W3C specification.


2. What is the difference between Selenium 3 and Selenium 4?

Key additions in Selenium 4:

  • W3C protocol compliance — no more JSON Wire Protocol; more predictable cross-browser behaviour
  • Selenium Manager — auto-downloads browser drivers; no manual chromedriver setup
  • Relative Locators — find elements relative to other elements (above(), below(), toLeftOf())
  • Chrome DevTools Protocol (CDP) — network interception, console logging, geolocation override
  • New window/tab APIdriver.switchTo().newWindow(WindowType.TAB)

3. What browsers does Selenium support?

Chrome (via ChromeDriver), Firefox (via GeckoDriver), Edge (via EdgeDriver), Safari (via SafariDriver on macOS), and Internet Explorer (deprecated). Chrome and Firefox are the most widely used in test automation.


4. How do you launch a Chrome browser in Selenium Java?

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;

ChromeOptions options = new ChromeOptions();
// options.addArguments("--headless=new"); // For CI
WebDriver driver = new ChromeDriver(options);
driver.get("https://example.com");

Selenium 4 does not require setting the system property for ChromeDriver location.


5. How do you close and quit the browser?

driver.close();  // Closes the current window only
driver.quit();   // Closes ALL windows and ends the WebDriver session

Always call driver.quit() in @AfterMethod (TestNG) or @After (JUnit) to release resources. close() only closes the active window — if multiple windows are open, the session remains.


6. What is the difference between driver.get() and driver.navigate().to()?

Both load a URL. navigate().to() is part of the Navigation interface and additionally supports navigate().back(), navigate().forward(), navigate().refresh(). Functionally equivalent for loading URLs.


Locators

7. What are the locator strategies in Selenium?

By.id("login-btn")
By.name("username")
By.className("error-message")
By.tagName("input")
By.linkText("Forgot password?")
By.partialLinkText("Forgot")
By.cssSelector("[data-test='submit']")
By.xpath("//button[contains(text(),'Login')]")

Preference order: ID → CSS Selector → XPath. Avoid tagName and className alone — too broad.


8. CSS Selector vs XPath — when to use which?

CSS Selector:

  • Faster execution
  • Cleaner, more readable syntax
  • Cannot traverse up the DOM (no parent selection)

XPath:

  • Can traverse the DOM in any direction (up, down, sibling)
  • Supports text-based selection: contains(text(), 'Submit')
  • Required when CSS cannot express the locator

Use CSS first. Use XPath when CSS cannot express what you need.


9. Write XPath to find a button containing the text "Add to Cart".

By.xpath("//button[contains(text(), 'Add to Cart')]")
// or with normalize-space for whitespace tolerance:
By.xpath("//button[normalize-space()='Add to Cart']")

10. What is an absolute XPath vs a relative XPath?

<!-- Absolute: starts from root, brittle -->
/html/body/div[1]/form/input[2]

<!-- Relative: starts from anywhere in DOM, robust -->
//input[@id='username']
//form[@class='login-form']//button

Always use relative XPath. Absolute XPath breaks with any DOM structural change.


11. How do you find an element by partial attribute value in CSS?

// Attribute starts with
By.cssSelector("[id^='product-']")

// Attribute ends with
By.cssSelector("[class$='-active']")

// Attribute contains
By.cssSelector("[data-test*='submit']")

Waits

12. What are the three types of waits in Selenium?

Implicit Wait: Applied globally to every findElement call. Driver waits up to the specified time before throwing NoSuchElementException.

Explicit Wait: Targeted wait for a specific condition on a specific element using WebDriverWait and ExpectedConditions.

Fluent Wait: Extends explicit wait with polling interval and ignored exceptions.


13. When should you use explicit wait vs implicit wait?

Always prefer explicit wait. Implicit wait applies globally and mixes unpredictably with explicit wait — they should never be used together. Explicit wait is precise, predictable, and targets the exact element and condition you are waiting for.


14. Write an explicit wait that waits for a button to be clickable.

WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));
WebElement button = wait.until(
    ExpectedConditions.elementToBeClickable(By.id("submit-btn"))
);
button.click();

15. What is a FluentWait?

Wait<WebDriver> fluentWait = new FluentWait<>(driver)
    .withTimeout(Duration.ofSeconds(15))
    .pollingEvery(Duration.ofSeconds(2))
    .ignoring(NoSuchElementException.class);

WebElement element = fluentWait.until(
    d -> d.findElement(By.id("dynamic-result"))
);

FluentWait checks the condition every 2 seconds, ignores NoSuchElementException during polling, and times out after 15 seconds. Useful for elements that appear intermittently.


16. What is a StaleElementReferenceException and how do you fix it?

Occurs when a previously found element is no longer attached to the DOM — usually because the page or part of the DOM was refreshed after findElement() was called.

Fix: Re-find the element inside the interaction:

// WRONG
WebElement element = driver.findElement(By.id("result"));
driver.navigate().refresh();
element.click();  // Stale!

// CORRECT — re-find after refresh
driver.navigate().refresh();
wait.until(ExpectedConditions.presenceOfElementLocated(By.id("result")));
driver.findElement(By.id("result")).click();

Interactions

17. How do you handle dropdowns in Selenium?

import org.openqa.selenium.support.ui.Select;

Select dropdown = new Select(driver.findElement(By.id("country")));

dropdown.selectByVisibleText("India");   // Select by displayed text
dropdown.selectByValue("IN");            // Select by option value attribute
dropdown.selectByIndex(2);              // Select by index (0-based)

// Get all options
List<WebElement> options = dropdown.getOptions();
// Get selected option
String selected = dropdown.getFirstSelectedOption().getText();

18. How do you handle checkboxes and radio buttons?

WebElement checkbox = driver.findElement(By.id("terms-checkbox"));

// Check if selected
boolean isChecked = checkbox.isSelected();

// Click to toggle
if (!isChecked) {
    checkbox.click();
}

19. How do you handle file upload?

WebElement fileInput = driver.findElement(By.cssSelector("input[type='file']"));
fileInput.sendKeys("/absolute/path/to/file.pdf");
// No need to click the file input — sendKeys handles it

20. How do you perform keyboard actions in Selenium?

import org.openqa.selenium.Keys;
import org.openqa.selenium.interactions.Actions;

// Tab key
driver.findElement(By.id("email")).sendKeys(Keys.TAB);

// Enter key
driver.findElement(By.id("email")).sendKeys("test@test.com" + Keys.ENTER);

// Keyboard shortcut (Ctrl+A, Ctrl+C)
Actions actions = new Actions(driver);
actions.keyDown(Keys.CONTROL)
       .sendKeys("a")
       .keyUp(Keys.CONTROL)
       .perform();

21. How do you perform mouse actions in Selenium?

Actions actions = new Actions(driver);

// Hover
actions.moveToElement(driver.findElement(By.id("menu-item"))).perform();

// Double click
actions.doubleClick(driver.findElement(By.id("cell"))).perform();

// Right click (context menu)
actions.contextClick(driver.findElement(By.id("item"))).perform();

// Drag and drop
WebElement source = driver.findElement(By.id("drag-source"));
WebElement target = driver.findElement(By.id("drop-target"));
actions.dragAndDrop(source, target).perform();

Windows, Frames, and Alerts

22. How do you switch between browser windows/tabs?

// Store the original window handle
String originalWindow = driver.getWindowHandle();

// Click something that opens a new tab
driver.findElement(By.id("open-link")).click();

// Wait for new window and switch to it
wait.until(ExpectedConditions.numberOfWindowsToBe(2));
for (String handle : driver.getWindowHandles()) {
    if (!handle.equals(originalWindow)) {
        driver.switchTo().window(handle);
        break;
    }
}

// Do work in new window...

// Switch back to original
driver.switchTo().window(originalWindow);

23. How do you handle iFrames?

// Switch to iframe by name or id
driver.switchTo().frame("payment-iframe");

// Switch by index (0-based)
driver.switchTo().frame(0);

// Switch by WebElement
WebElement frame = driver.findElement(By.cssSelector("iframe.payment-frame"));
driver.switchTo().frame(frame);

// Return to main page
driver.switchTo().defaultContent();
// or return to parent frame only:
driver.switchTo().parentFrame();

24. How do you handle JavaScript alerts?

// Wait for alert
wait.until(ExpectedConditions.alertIsPresent());
Alert alert = driver.switchTo().alert();

// Get text
String alertText = alert.getText();

// Accept (OK)
alert.accept();

// Dismiss (Cancel)
alert.dismiss();

// Enter text in prompt alert
alert.sendKeys("my input");
alert.accept();

Advanced Topics

25. What is the Page Object Model?

POM is a design pattern that creates a class for each web page or component in the application. Each class encapsulates:

  • Element locators (as private By constants)
  • Methods for interacting with those elements (as public methods)

Test classes use Page Object methods — they never interact with WebDriver directly. This separates test logic (what to verify) from page interaction logic (how to interact). Changes to the UI only require updating the Page Object, not every test.


26. What is PageFactory and @FindBy?

import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.PageFactory;

public class LoginPage {
    
    @FindBy(id = "username")
    private WebElement usernameField;
    
    @FindBy(id = "password")
    private WebElement passwordField;
    
    @FindBy(css = "[data-test='login-btn']")
    private WebElement loginButton;
    
    public LoginPage(WebDriver driver) {
        PageFactory.initElements(driver, this);
    }
    
    public void login(String username, String password) {
        usernameField.sendKeys(username);
        passwordField.sendKeys(password);
        loginButton.click();
    }
}

PageFactory.initElements() initialises all @FindBy annotated fields lazily — elements are found when first accessed.


27. What are TestNG annotations and their execution order?

@BeforeSuite    → Once before the entire test suite
@BeforeTest     → Once before each <test> tag in testng.xml
@BeforeClass    → Once before the first test in a class
@BeforeMethod   → Before EACH test method
@Test           → The actual test
@AfterMethod    → After EACH test method
@AfterClass     → Once after the last test in a class
@AfterTest      → Once after each <test> tag
@AfterSuite     → Once after the entire suite

@BeforeMethod / @AfterMethod is where browser setup and teardown goes for parallel-safe tests.


28. How do you run tests in parallel with TestNG?

In testng.xml:

<suite name="Suite" parallel="methods" thread-count="4">
    <test name="Parallel Tests">
        <classes>
            <class name="com.qa.tests.LoginTest"/>
        </classes>
    </test>
</suite>

For parallel-safe tests, the WebDriver instance must be stored in a ThreadLocal:

public class BaseTest {
    private static ThreadLocal<WebDriver> driverThreadLocal = new ThreadLocal<>();
    
    public static WebDriver getDriver() { 
        return driverThreadLocal.get(); 
    }
    
    @BeforeMethod
    public void setUp() {
        driverThreadLocal.set(new ChromeDriver());
    }
    
    @AfterMethod
    public void tearDown() {
        getDriver().quit();
        driverThreadLocal.remove();
    }
}

29. What is a data-driven test in TestNG?

@DataProvider(name = "loginData")
public Object[][] provideLoginData() {
    return new Object[][] {
        {"standard_user", "secret_sauce", true},
        {"locked_out_user", "secret_sauce", false},
        {"invalid_user", "bad_pass", false}
    };
}

@Test(dataProvider = "loginData")
public void testLogin(String username, String password, boolean expectedSuccess) {
    LoginPage loginPage = new LoginPage(driver);
    loginPage.navigate();
    loginPage.login(username, password);
    
    if (expectedSuccess) {
        Assert.assertTrue(new DashboardPage(driver).isOnDashboard());
    } else {
        Assert.assertTrue(loginPage.isErrorDisplayed());
    }
}

30. How do you take a screenshot in Selenium?

import org.apache.commons.io.FileUtils;

File screenshot = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(screenshot, 
    new File("screenshots/failure_" + System.currentTimeMillis() + ".png"));

Add to @AfterMethod with the TestNG ITestResult parameter to capture screenshots only on failure.


Framework and Design Questions

31. How do you read test data from an Excel file?

Use Apache POI:

<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi-ooxml</artifactId>
    <version>5.2.5</version>
</dependency>
Workbook workbook = WorkbookFactory.create(new File("testdata.xlsx"));
Sheet sheet = workbook.getSheet("LoginData");
Row row = sheet.getRow(1);
String username = row.getCell(0).getStringCellValue();

32. How do you implement a custom retry mechanism for flaky tests?

TestNG's IRetryAnalyzer:

public class RetryAnalyzer implements IRetryAnalyzer {
    private int retryCount = 0;
    private static final int MAX_RETRIES = 2;
    
    @Override
    public boolean retry(ITestResult result) {
        if (retryCount < MAX_RETRIES) {
            retryCount++;
            return true;  // Retry
        }
        return false;  // Stop retrying
    }
}

// Apply to test
@Test(retryAnalyzer = RetryAnalyzer.class)
public void testFlaky() { ... }

33. What is the Singleton design pattern and how is it used in Selenium frameworks?

Singleton ensures only one instance of a class exists. In Selenium frameworks, it is used for WebDriver management — ensuring only one driver is active per test thread:

public class DriverManager {
    private static ThreadLocal<WebDriver> driver = new ThreadLocal<>();
    
    public static WebDriver getDriver() { return driver.get(); }
    public static void setDriver(WebDriver d) { driver.set(d); }
    public static void quitDriver() {
        if (driver.get() != null) {
            driver.get().quit();
            driver.remove();
        }
    }
}

34. How do you handle dynamic elements with changing IDs?

Use stable attributes instead of dynamic IDs:

// BAD — ID changes on every page load
By.id("element-7f3a9c")

// GOOD — text content is stable
By.xpath("//button[contains(text(), 'Submit')]")

// GOOD — data attribute is stable (if developers add them)
By.cssSelector("[data-action='submit-form']")

// GOOD — parent + relative position
By.xpath("//div[@class='payment-section']//button[1]")

35. What causes flaky tests and how do you fix them?

Causes:

  1. Timing issues — Fixed with explicit waits, never Thread.sleep()
  2. Shared test data — Tests modifying the same database records interfere with each other. Fix: isolated test data per test run.
  3. Browser state leaking — Cookies, local storage from previous tests. Fix: fresh browser per test (@BeforeMethod setup).
  4. Environment instability — Fix: retry mechanism (2 retries max), better environment.
  5. Dynamic element IDs — Fix: stable locators.

36–60. Rapid Round

36. findElement() returns one element or throws; findElements() returns a list (empty if none).

37. WebElement.getAttribute("value") returns the current value of an input field; WebElement.getText() returns visible text.

38. isDisplayed() checks visibility; isEnabled() checks interactability; isSelected() checks selection state.

39. driver.getTitle() returns the page title string.

40. driver.getCurrentUrl() returns the current page URL.

41. Execute JavaScript: ((JavascriptExecutor) driver).executeScript("window.scrollTo(0, document.body.scrollHeight)");

42. Scroll to element: ((JavascriptExecutor) driver).executeScript("arguments[0].scrollIntoView(true);", element);

43. Click with JavaScript (bypass visibility/offset issues): ((JavascriptExecutor) driver).executeScript("arguments[0].click();", element);

44. Get all links: driver.findElements(By.tagName("a")) — returns list of all anchor elements.

45. Broken links: get all anchor elements, call getAttribute("href"), send HTTP request to each, check for 4xx responses.

46. WebDriver is the interface; ChromeDriver, FirefoxDriver are implementations.

47. TestNG groups: @Test(groups = {"smoke"}) — run with <groups><run><include name="smoke"/></run></groups> in testng.xml.

48. Assert.assertEquals(actual, expected) — hard fail, stops test immediately. SoftAssert.assertEquals() — collects failures and reports all at end.

49. Handling SSL certificates: ChromeOptions.setAcceptInsecureCerts(true) or ChromeOptions.addArguments("--ignore-certificate-errors").

50. driver.manage().window().maximize() — maximise window.

51. Store cookies: driver.manage().getCookies(). Add cookie: driver.manage().addCookie(new Cookie("session", "token123")).

52. Keys.chord() for combination keys: element.sendKeys(Keys.chord(Keys.CONTROL, "a")) selects all text.

53. Headless Chrome: options.addArguments("--headless=new", "--no-sandbox", "--disable-dev-shm-usage").

54. Relative locator (Selenium 4): driver.findElement(RelativeLocator.with(By.tagName("input")).above(By.id("email"))).

55. WebDriverWait default polling: every 500ms. Configurable via FluentWait.pollingEvery().

56. Read browser console logs: LogEntries logs = driver.manage().logs().get(LogType.BROWSER).

57. driver.manage().deleteAllCookies() — clear all cookies (useful before each test).

58. driver.switchTo().newWindow(WindowType.TAB) — open a new tab (Selenium 4).

59. Network interception (Selenium 4 CDP): intercept and modify network requests using HasDevTools and Chrome DevTools Protocol.

60. Selenium Grid enables running tests on remote machines or containers. Tests connect to the Hub, which distributes them to registered Nodes with the specified browser/OS combination.

Recommended Resource

QA Interview Kit

Interview prep kit with real-world QA and API scenarios.

999Get This Guide →

Related Posts

📝
Interview Prep
Apr 2026·10 min read

30 Performance Testing Interview Questions and Answers

Performance testing interview questions for QA roles — covering load testing, stress testing, JMeter, key metrics, and how to analyze results.

Read article →
📝
Interview Prep
Apr 2026·12 min read

35 Playwright Interview Questions (With Answers)

Playwright interview questions and answers for QA and SDET roles — covering setup, locators, waits, fixtures, API testing, and debugging.

Read article →
📝
Interview Prep
Apr 2026·11 min read

40 SQL Interview Questions for QA Engineers

SQL interview questions specifically for QA and SDET roles — covering SELECT, JOINs, aggregations, NULL handling, and data validation queries with answers.

Read article →