Top 40 Selenium Java Interview Questions and Answers for Automation Testers.

Preparing for a Selenium interview can be challenging, especially when interviewers expect both strong Selenium concepts and practical Java automation knowledge. In this article, I have covered the Top 40 Selenium Java interview questions and answers for automation testers, ranging from basic Selenium concepts to real-world automation scenarios.

These questions cover important topics such as Selenium WebDriver, locators, waits, browser and window handling, alerts, frames, Actions class, JavaScriptExecutor, screenshots, file handling, TestNG, Selenium Grid, and more.

Whether you are a beginner preparing for your first automation testing interview or an experienced tester looking to refresh your Selenium and Java skills, this article can help you to prepare more confidently and strengthen your understanding of Selenium automation.

Table of Contents

1. What is selenium?

Selenium is an open-source automation testing framework used to automate web applications. It supports multiple Browsers, Operating systems and languages.

2. What are Advantages of selenium?

  • it’s free and open-source tool.
  • Low-cost maintenance.
  • Reusability of code.
  • It supports multiple programming languages.
  • It supports multi browser and multi-OS
  • Automated testing is more reliable and more versatile
  • It’s mostly used for regression testing 
  • Minimal manual intervention
  • Can be used for mobile testing as well

3. What are Disadvantages of selenium?

  • No community supports – We have to communicate with online forum.
  • Support only web applications don’t support desktop applications.
  • No Built-in reporting facility.
  • Cannot handle OTP and Captcha.
  • We can do only functional testing.

4. What are Complexity with selenium?

  • No facility to deal with captcha.
  • Since selenium is a freeware tool, there is no direct support from selenium team.
  • Doesn’t support any non-web-based applications.
  • Don’t have any reporting related capabilities, you need to depend on third party tools.
  • Difficult to identify dynamic object.
  • Timeout resulting from synchronization problems.
  • You need to learn any one of native languages like (.net, java, c#, ruby, perl, python, php) to work efficiently
  • Working with frames.
  • Dealing with popup windows.
  • Unexpected error while launching the internet explorer: browser zoom level should be set to be 100% by default for the IE browser to overcome this error.
  • Cross browser testing issues.

5. What is mutation testing?

Mutation testing is software testing where we mutate (change/ edit) certain statement in program and check if the test cases are able to find error.

The change in mutant program is kept externally small so it does not affect overall objective of the program.

The goal of mutation testing is to develop effective test cases. It makes test cases robust.

Mutation testing also called fault-based testing.

6. What is the various component of selenium?

Selenium 3

  • Selenium IDE
  • Selenium RC
  • Selenium WebDriver
  • Selenium Grid

Selenium 4

7. Explain Selenium4 Enhancements

Selenium 4 introduced improvements based on the W3C WebDriver standard and added new features for modern web testing.

  • W3C WebDriver protocol: It improves communication between Selenium and web browsers using a standardized protocol.
  • Enhanced Selenium Grid: Provides improved architecture and support for distributed and parallel test execution.
  • Chrome DevTools Protocol (CDP): Selenium 4 provides APIs that allow automation to interact with browser DevTools capabilities. For example, you can interact with network-related functionality, browser console capabilities, performance information, etc.
  • New features: Includes relative locators, better window and tab management, and improved browser interaction capabilities.

8. Can we automate Captcha using selenium?

CAPTCHA is specifically designed to distinguish humans from automated programs, so Selenium should not be used to bypass or solve CAPTCHA challenges.

  • In test environments, CAPTCHA can be disabled or replaced with a test-friendly mechanism.
  • Test-specific tokens or bypass mechanisms can be provided by the development team for authorized testing.

9. What is the difference between getwindowhandles() and getwindowhandle()?

getWindowHandle()

Returns the unique ID (handle) of the currently active browser window/tab in String format.

String currentWindow = driver.getWindowHandle();
System.out.println(currentWindow);

getWindowHandles()

Returns the IDs of all currently open browser windows/tabs in Set<String> format.

Set<String> allWindows = driver.getWindowHandles();
System.out.println(allWindows);

10. How do you work with frames in Selenium?

An iframe (inline frame) is a webpage embedded inside another webpage You cannot interact with elements inside an iframe using selenium until you switch to that iframe.

There are three common ways to switch to a frame in Selenium.

Using frame index

driver.switchTo().frame(0);

Here, 0 means the first frame on the page

Using frame name or ID

driver.switchTo().frame("productFrame");

Using the iframe WebElement

WebElement frame = driver.findElement(By.id("productFrame")); 
driver.switchTo().frame(frame);

11. How to scroll webpage in selenium?

Using JavaScriptExecutor

scrollBy pixels

JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("window.scrollBy(0,500)");

This scrolls the page 500 pixels downward.

Scroll to the top

js.executeScript("window.scrollTo(0,0)");

Scroll to the bottom

js.executeScript("window.scrollTo(0, document.body.scrollHeight)");

Scroll until an element is visible

WebElement element = driver.findElement(By.id("footer"));
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("arguments[0].scrollIntoView();", element);

Using Selenium Actions

WebElement element = driver.findElement(By.id("footer"));
Actions actions = new Actions(driver);
actions.scrollToElement(element).perform();

12. What is fundamental difference between XPath and css selector?

The fundamental difference between XPath and css selector is using XPaths we can traverse up and down in the document. Whereas using CSS selector we can only move downwards in the document.

13. What is Selenium Grid?

Selenium Grid is a tool that allows you to run Selenium automation tests on multiple browsers, operating systems, and machines at the same time.

In simple words, instead of running all your tests on a single computer, Selenium Grid allows you to distribute the tests across multiple machines and execute them in parallel.

14. What are the types of waits available in Selenium WebDriver?

Implicit Waits

driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(10));

Explicit Waits

WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));
WebElement loginButton = wait.until(ExpectedConditions.elementToBeClickable(By.id("login")));
loginButton.click();

Some commonly used conditions are:

ExpectedConditions.visibilityOfElementLocated(...)
ExpectedConditions.elementToBeClickable(...)
ExpectedConditions.presenceOfElementLocated(...)
ExpectedConditions.invisibilityOfElementLocated(...)
ExpectedConditions.titleContains(...)
ExpectedConditions.alertIsPresent()
ExpectedConditions.frameToBeAvailableAndSwitchToIt(...)

Fluent Waits

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

WebElement element = wait.until(driver -> driver.findElement(By.id("username")));

Here Selenium:

  • waits up to 20 seconds
  • checks for every 2 seconds
  • ignores NoSuchElementException while polling

15. What is the difference between Implicit & Explicit wait?

  • Implicit wait applies for all the elements and all the tests. Like if we give 10 seconds of implicit wait then it will wait for 10 seconds for each element before throwing NoSuchElementException. 
  • While Explicit wait can be applied for any particular WebElement for which you want extra wait time.

16. What is the Assert and SoftAssert and difference?

In the case of Assert, if the Assert condition fails, the current test method stops executing immediately and the test case is marked as failed. These assertions are used as checkpoints for testing or validating business-critical transactions.

Commonly used Assert methods:

Assert.assertEquals(actual, expected);
Assert.assertNotEquals(actual, expected);
Assert.assertTrue(condition);
Assert.assertFalse(condition);
Assert.assertNull(object);
Assert.assertNotNull(object);
Assert.fail("Test failed");

In case of SoftAssert, tests will continue to run until the last test is executed even if assert conditions fails. Soft Asserts will report the errors at the end of the tests. Testers need to invoke the assertAll() method to view the results.

SoftAssert softAssert = new SoftAssert();
softAssert.assertEquals(actual, expected);
softAssert.assertAll();

17. What are Different types of locators in selenium?

In Selenium, locators are used to identify web elements on a webpage so that Selenium can interact with them.

Selenium provides 8 traditional locator strategies:

Id – Similar to class, we can also identify elements by using the ‘id’ attribute.
name – Name attribute can also identify an element
className – A className operator uses a class attribute to identify an object.
linkText – Text used in hyperlinks can also locate element
partialLinkText – Part of the text in the link can also identify an element
tagName – We can also use a tag to locate elements
cssSelector – CSS is used to create style rules for webpages and can be used to identify any web element.
xpath – xpath is the language used to query the XML document. The same can uniquely identify the

18. What is the difference driver.close() and driver.quit()

driver.close()

The driver.close() command is used to close the current browser window having focus. In case there is only one browser open then calling driver.close() quits the whole browser session.

driver.quit()

The driver.quit() is used to quit the whole browser session along with all the associated browser windows, tabs and pop-ups.

19. What do you mean by Exceptions in Java?

Exception is any interruption in our normal flow of execution. Like if we are running anything and we got issues in our script this we called an Exception, In java there are 2 types of exception Run Time & Compile Time. (Checked & Unchecked exceptions)

20. Why we use JavaScript in selenium?

 Core Scenarios Requiring JavaScriptExecutor

Interacting with Hidden, Overlapped, or Disabled Elements:

If an element is hidden behind another layer, or disabled by custom logic, native Selenium will throw an exception (such as ElementClickInterceptedException or ElementNotInteractableException). JavaScriptExecutor bypasses browser restrictions to perform forced actions directly on the DOM.

Advanced Page Scrolling:

Native Selenium lacks dedicated window scrolling functions. so we use JavaScriptExecutor to scroll to a specific position or bring a particular element into view by scrolling to specific coordinate points or smoothly tracking elements.

Retrieving Page Metadata and Content:

It allows you to fetch background details that Selenium cannot access directly, such as the document’s innerText, actual page title, URL context, or window load performance metrics.

Manipulating Dynamic Content & AJAX:

You can modify element attributes, remove restrictions, make hidden elements visible, and interact with AJAX or jQuery operations that run asynchronously in the background.

21. What is the difference between findelement & findelements?

findelement will give the first appearance of that element which matches our locator, whereas findelements will give us list of all the elements which is present over the webpage and matching our locator.

And if we don’t find the element using findelement will give us NoSuchElementException, Whereas by using findelements will return NULL/Empty list.

22. Do you heard about Priority in TestNg can we set -ve priority?

Yes, like priority is 0, -1, TestNg will run -1 then 0 then 1. And if we have any @test which is not having any priority set, then in that case it will search via alphabetic order whichever comes first and execute test respectively.

23. Can you explain TestNG?

TestNG is an open-source test automation framework for Java.
The NG in TestNG stands for ‘Next Generation.
It is mainly used by Dev/QA for maintain the code easily and for unit testing.
It provides lots of benefits to us like 

  • We can create a suite and we can write all the required Test Cases in one go only using that suite. 
  • We can group our Test Cases
  • We can set priority to Test Cases
  • We can run our Test Cases in parallel mode
  • We can generate good reports via TestNG. 
  • We can write functionality depends on methods, depends on group. 
  • We can run single Test Case multiple time with single set of data or multiple set of Data.

24. What are the types of frameworks in Selenium?

  • Data-driven Testing Framework
  • Keyword Driven Testing Framework
  • Hybrid Testing Framework
  • Behaviour Driven Development Testing Framework
  • Linear Scripting Framework
  • Modular Testing Framework

25. Is the complete automation testing can be done, if not explain why?

No, we cannot do the 100% automation testing, we cannot handle the Captcha and OTP functionality

26. How to execute only failed test cases?

TestNG will create one .xml file for failed test cases in test-output folder with name testng-failed.xml

You can run this .xml file it will run only the failed test cases.

27. What are Different annotations in testNG?

  • @Test: Marks a class or a method as a part of the test.
  • @DataProvider: Marks a method as supplying data for a test method. The annotated method must return an Object[ ][ ], where each Object[ ] can be assigned the parameter list of the test method. The @Test method that wants to receive data from this DataProvider needs to use a dataProvider name equals to the name of this annotation.
  • @Factory: Marks a method as a factory that returns objects that will be used by TestNG as Test classes. The method must return Object[ ].
  • @Listeners: Defines listeners on a test class.
  • @Parameters: Describes how to pass parameters to a @Test method.
  • @BeforeSuite: Executes once before all tests in the entire TestNG suite.
  • @AfterSuite: Executes once after all tests in the entire TestNG suite.
  • @BeforeClass: Executes once before the first test method in a class.
  • @AfterClass: Executes once after all test methods in a class have completed.
  • @BeforeTest: Executes before the first test method belonging to a <test> tag in the TestNG XML file.
  • @AfterTest: Executes before the first test method belonging to a <test> tag in the TestNG XML file.
  • @BeforeMethod: Executes before each @Test method in the class.
  • @AfterMethod: Executes after each @Test method in the class.
  • @BeforeGroups: The list of groups that this configuration method will run before. This method is guaranteed to run shortly before the first test method that belongs to any of these groups is invoked.
  • @AfterGroups: The list of groups that this configuration method will run after. This method is guaranteed to run shortly after the last test method that belongs to any of these groups is invoked.

28. How to take screenshot in selenium?

In Selenium, we use the TakesScreenshot interface to capture screenshots.

Screenshot of a fullpage

WebDriver driver = new ChromeDriver();

driver.get("https://www.google.com");

TakesScreenshot ts = (TakesScreenshot) driver;

File source = ts.getScreenshotAs(OutputType.FILE);
File destination = new File("screenshots/google.png");

Files.copy(source.toPath(), destination.toPath());

driver.quit();

Screenshot of a specific element

Selenium 4 also allows taking a screenshot of an individual element:

WebElement element = driver.findElement(By.id("logo"));

File source = element.getScreenshotAs(OutputType.FILE);
File destination = new File("screenshots/logo.png");

Files.copy(source.toPath(), destination.toPath());

29. How to stop loading of Webpage?

driver.findElement(By.tagName("body")).sendKeys("Keys.ESCAPE");

We can stop a webpage from loading, by using JavaScript:

JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("return window.stop");

30. How to set custom browser window size?

In Selenium, you can set a custom browser window size using the Dimension class and setSize() method.

Dimension d = new Dimension(480,620);
driver.manage().window().setSize(d);

31. What are the different Exceptions are available selenium?

  • NoSuchElementException
  • NoSuchWindowException
  • NoSuchFrameException
  • NoAlertPresentException
  • ElementNotVisibleException
  • ElementNotSelectableException
  • ElementNotInteractableException
  • ElementClickInterceptedException
  • TimeoutException
  • StaleElementReferenceException
  • WebDriverException
  • InvalidSelectorException
  • InvalidArgumentException
  • InvalidElementStateException

32. What is the difference between driver.get(“url”) and driver.navigate.to(“url”)?

driver.get(): To open an URL and it will wait till the whole page gets loaded.

driver.navigate.get(): To navigate to an URL and It will not wait till the whole page gets loaded.

33. How to handle mouse actions in selenium?

In Selenium, mouse actions are handled using the Actions class. It allows us to perform actions such as hover, right-click, double-click, drag-and-drop, and click-and-hold.

Actions actions = new Actions(driver);

actions.click(element).perform();
actions.doubleClick(element).perform();
actions.contextClick(element).perform();//performs right click on element
actions.moveToElement(element).perform();//performs mouse hover on element
actions.clickAndHold(element).perform();
actions.release().perform();
actions.dragAndDrop(source, target).perform();

34. How to handle keyboard events in selenium?

In Selenium, keyboard events are handled using the Actions class and the Keys class.

Actions actions = new Actions(driver);

//perform ENTER action from keyboard
actions.sendKeys(Keys.ENTER).perform();

//perform Ctrl + A
actions.keyDown(Keys.CONTROL)
       .sendKeys("a")
       .keyUp(Keys.CONTROL)
       .perform();

35. What is the difference between Absolute XPath and Relative XPath?

Absolute XPath

Absolute XPath starts from the root of the HTML document and follows the complete DOM hierarchy. It Starts with //

/html/body/div/div/form/input

Relative XPath

Relative XPath starts from any location in the DOM. It Starts with //

//input[@id='username']

36. How can we handle multiple tabs in selenium?

In Selenium, multiple tabs/windows are handled using window handles. Selenium treats each browser tab/window as a separate window handle.

String parentWindow = driver.getWindowHandle();

Set<String> allWindows = driver.getWindowHandles();

for (String window : allWindows) {
    if (!window.equals(parentWindow)) {
        driver.switchTo().window(window);
        break;
    }
}

37. How to perform read operation from Excel sheet?

In Selenium with Java, Excel read/write operations are commonly handled using Apache POI. Selenium itself does not provide Excel handling functionality.

Read data from Excel

FileInputStream fis = new FileInputStream("TestData.xlsx");

Workbook workbook = new XSSFWorkbook(fis);
Sheet sheet = workbook.getSheet("Login");

String username = sheet.getRow(1).getCell(0).getStringCellValue();
String password = sheet.getRow(1).getCell(1).getStringCellValue();

System.out.println(username);
System.out.println(password);

workbook.close();
fis.close();

38. How to perform write operation to Excel sheet?

FileInputStream fis = new FileInputStream("TestData.xlsx");

Workbook workbook = new XSSFWorkbook(fis);
Sheet sheet = workbook.getSheet("Login");

sheet.getRow(1).createCell(2).setCellValue("Pass");

FileOutputStream fos = new FileOutputStream("TestData.xlsx");
workbook.write(fos);

workbook.close();
fis.close();
fos.close();

39. Difference between Actions and Action?

Actions

  • Actions is a class.
  • It is Used to build/perform complex user interactions
  • Provides methods like click(), doubleClick(), moveToElement(), dragAndDrop()

Action

  • Actions is an interface
  • Represents a single built action sequence
  • Mainly used when you want to store the built action

40. We can handle the keyboard action by using Action class and Robot class then what is the difference in both?

Actions

  • Actions is a selenium class present in org.openqa.selenium.interactions.Actions
  • Works mainly with browser/WebElement interactions
  • Sends keyboard events through Selenium/WebDriver
  • Commonly used for browser keyboard actions

Robot

  • Robot is a java class present in java.awt.Robot
  • Controls the actual OS keyboard/mouse
  • Sends native OS-level input events
  • Useful for OS-level dialogs and applications
Previous Post

Leave a Reply

Your email address will not be published. Required fields are marked *

About Us

We share practical insights, helpful guides, and the latest updates to support your learning journey. Our focus is on delivering clear, actionable content that you can easily apply in real-world situations.

Most Recent Posts

Newsletter

Follow us. Learn more. Automate smarter.

Useful Links

Contact

Pune, Maharashtra

info@codetoautomate.com

Sign Up

Stay updated with fresh content.

© 2026 CodeToAutomate. All Rights Reserved. | Privacy Policy | Terms & Conditions | Disclaimer