Prepare for CTS interviews with 484 curated questions. The answer examples below explain key concepts; personalize project and experience responses truthfully. These are independent study resources, not official company interview materials.
Interview Questions with Answer Explanations
These study answers summarize the associated PDF material. Adapt personal, project and experience details to your own background.
Explain the framework functionality in depth
Walk through one test end to end: the developer or tester triggers execution locally or through CI; Maven resolves dependencies and invokes the test runner; TestNG/Cucumber selects tests; setup reads environment configuration and creates a browser session; page objects perform actions; assertions verify outcomes; listeners/hooks capture failures and evidence; reporting writes HTML/XML; teardown closes the WebDriver session. The architecture separates test intent from page details and reusable infrastructure. CI / Eclipse -> Maven -> TestNG/Cucumber runner -> hooks / DriverFactory -> page objects + utilities + test data -> Selenium WebDriver -> browser -> assertions/listeners -> reports.
Your role in the automation team
Answer using your actual responsibilities. A QA/Test Lead may review requirements, select automation candidates, design/maintain framework components, write or review scripts, manage test data, triage failures, coordinate defect resolution, monitor regression runs, mentor team members, and communicate release risks. Give one real example of your contribution and its outcome; do not claim duties you did not perform.
Do you know Robot Framework?
Robot Framework is an open-source, keyword-driven automation framework. It provides readable test cases and supports libraries for web/API and other testing. SeleniumLibrary supports Selenium-based browser automation; Browser is a Playwright-based option. Robot Framework is not the same as Selenium WebDriver: Robot Framework is the test authoring/execution framework, while Selenium is a browser automation API. *** Settings *** Library SeleniumLibrary *** Test Cases *** Open Example Open Browser https://example.com chrome Title Should Be Example Domain Close Browser Note: If you have not used it hands-on, say you understand the concepts but have not used it professionally.
Explain TestNG XML structure
testng.xml defines a suite and its test blocks. It can specify parameters, classes/packages, groups, listeners, exclusions, and parallel execution. The suite tag is the top-level container; each test tag can select classes. Fully qualified Java class names are used in class name attributes. <!DOCTYPE suite SYSTEM "https://testng.org/testng-1.0.dtd"> <suite name="Regression" parallel="tests" thread-count="2"> <parameter name="browser" value="chrome"/> <test name="Login"> <classes> <class name="tests.LoginTest"/> </classes> </test> </suite> Java, Selenium & TestNG Interview Questions 1–100 · Saravana Tech.
How do you connect to a database in Java?
Use JDBC (Java Database Connectivity). The usual steps are: have the vendor JDBC driver on the classpath; build the JDBC URL; open a Connection; create a PreparedStatement; bind parameters; execute a query/update; read the ResultSet if it is a query; close resources. Use try-with-resources and keep credentials outside source control.
Database URL types apart from http://
Database URLs are not usually HTTP URLs. In Java JDBC, common forms are jdbc:mysql://host:3306/database, jdbc:postgresql://host:5432/database, jdbc:sqlserver://host:1433;databaseName=database, jdbc:oracle:thin:@//host:1521/service, and jdbc:sqlite:path/to/file.db. The exact syntax depends on the database and driver.
Is it mandatory to close Statement in DB code?
Yes, close ResultSet, Statement/PreparedStatement, and Connection when finished. They consume resources; leaks can exhaust database cursors or connection pools. Prefer try-with-resources, which closes resources even when an exception occurs.
Write database connection code and walk through it
The URL identifies the database. DriverManager creates a connection. PreparedStatement represents parameterized SQL and helps avoid SQL injection. setInt binds a value to the first ? placeholder. executeQuery returns a ResultSet. next advances row by row, and getString/getInt reads columns. try- with-resources closes everything.
Explain the List interface
List is an ordered Java collection. It supports index-based access and normally allows duplicate elements. Common implementations are ArrayList and LinkedList. Common methods include add, get, set, remove, size, contains, and iterator.
List interface usage with Selenium Select
Select represents a native HTML <select>. Its getOptions() method returns List<WebElement>, which lets you inspect the options. The List stores the option elements; the Select object provides selectByVisibleText, selectByValue, and selectByIndex.
Can you call selectByVisibleText/selectByIndex on a List reference?
No. List<WebElement> has collection methods such as get() and size(), but not Selenium Select methods. Those methods belong to the Select class. Use the Select object to select options in a native HTML select.
Select dropdown values without those Select methods
For a native select, find its option elements and click the option matching the required text. For a custom dropdown built from div/li/button elements, click the dropdown and then click the matching option. Inspect the HTML first; the native Select class does not work on custom dropdowns.
Select the second dropdown value by index
Selenium uses zero-based indexes: index 0 is the first option, index 1 is the second. The element must be a native HTML select. Java, Selenium & TestNG Interview Questions 1–100 · Saravana Tech Select s = new Select(driver.findElement(By.id("country"))); s.selectByIndex(1); // second option.
How do you parameterize in TestNG?
TestNG supports XML parameters through @Parameters and data-driven execution through.
Give an example of DataProvider
DataProvider returns a two-dimensional Object array. TestNG invokes the annotated test once for each row, passing row values as method arguments.
Object class and arrays
Object is the root superclass of ordinary Java classes. Arrays are also objects, so an array reference can be assigned to a variable of type Object. Object provides methods such as toString, equals, hashCode, getClass, wait, notify, and notifyAll. Array types are special JVM types; they are not declared as normal classes.
How did you parameterize data in your framework?
Describe the real implementation: for example, DataProvider for combinations, testng.xml for browser/environment, Excel/CSV/JSON for test data, and properties/environment variables for configuration. Explain how rows are mapped to test arguments and how test data is isolated. Adapt this answer to your actual project.
Why JXL instead of Apache POI?
JXL is an older library that mainly supports .xls and has limited modern Excel feature support. Apache POI supports both .xls and .xlsx and is generally preferred for new Java projects. If your existing project uses JXL, explain that it may be legacy code or an .xls-only constraint; do not claim JXL is more capable.
Difference between JXL and Apache POI
JXL primarily supports Excel 97–2003 .xls files. Apache POI supports .xls through HSSF and .xlsx through XSSF and has broader workbook, formatting, and formula support. POI is more suitable for modern Excel files. For large .xlsx files, consider POI streaming APIs.
JXL sample code and method walkthrough
Legacy JXL example: Workbook.getWorkbook(File) opens the workbook; getSheet(0) selects the first sheet; getRows/getColumns report dimensions; getCell(column,row) takes the column first and row second, both zero-based; getContents returns cell text; close releases resources. JXL does not read .xlsx. Workbook wb = null; try { wb = Workbook.getWorkbook(new File("data.xls")); Sheet sh = wb.getSheet(0);.
What reports do you generate?
Common choices include TestNG HTML/XML reports, Cucumber reports, ExtentReports, Allure, and CI summaries. Explain the report you actually use, including pass/fail/skip status, execution duration, failure stack trace, screenshots, logs, and where the report is published. Java, Selenium & TestNG Interview Questions 1–100 · Saravana Tech.
Ways to create customized HTML reports
Options include writing HTML directly from Java, transforming XML test results into HTML with XSLT, or using a reporting library/template engine. A report should escape inserted text and show test name, status, duration, failure details, and links to evidence. Writing HTML manually is possible, but a reporting library is easier to maintain for larger suites.
Can you design a framework? What would you consider?
Assess application type, test inventory, risk, stability, browser/environment matrix, data setup, test frequency, team skills, CI, reporting, maintainability, and execution time. Start with a small end-to-end slice. Separate runner, driver management, page objects, data/config, utilities, assertions/listeners, reporting, and CI. Add parallel execution only after driver/data/report components are thread-safe.
Compare Selenium JAR versions 2.45.0 and 2.46.0
These appear to be legacy Selenium 2 versions. The exact fixes and features between them depend on the specific artifact and release notes. Do not guess features from the version numbers alone; identify whether the interviewer means selenium-java or another JAR and compare its official release notes. Selenium 2 is obsolete for new projects.
Find India and click the checkbox beside it when its position changes
Anchor the locator on the stable text, locate the nearest shared row/container, and find the checkbox inside it. This avoids relying on a changing row index or screen coordinate. The exact ancestor depends on the actual DOM.
Verify the expected heading colour
Use getCssValue("color") to read the computed CSS value. Browsers commonly return rgb()/rgba() even if the CSS source uses a hex colour. Compare normalized expected and actual values.
Find an element in three nested frames
Switch from the top document into frame 1, then frame 2, then frame 3, waiting for each frame. Find the element only after entering the innermost frame. Return to the main document with defaultContent().
What is WebElement: interface or class?
WebElement is an interface in Selenium's Java API representing a DOM element. It declares methods such as click, sendKeys, getText, getAttribute, getCssValue, isDisplayed, isEnabled, and isSelected. WebDriver implementations return objects that implement this interface.
Compile-time vs runtime polymorphism
Compile-time polymorphism is commonly achieved through method overloading: the compiler selects the method based on parameter types/count. Runtime polymorphism is achieved through overriding: the actual object's class determines which overridden instance method executes.
Why might an element not be identifiable if it is not an alert?
Possible reasons include wrong/stale locator, element in an iframe or shadow DOM, wrong window, element not loaded, hidden/conditionally rendered content, duplicate matches, wrong page state, or incorrect selector syntax. Inspect the DOM, count matches, verify frame/window context, and wait for the relevant condition.
Where do you keep locators in your framework?
In a POM framework, page-specific locators usually belong in that page's class; reusable widgets can have component classes. This keeps locators close to their actions and avoids scattering selectors across test cases. Avoid a single giant locator file unless the project has a clear reason for it. Java, Selenium & TestNG Interview Questions 1–100 · Saravana Tech.
Pass data without sendKeys
For ordinary user-like typing, sendKeys is the preferred WebDriver API. Alternatives depend on the requirement: Actions for keyboard interaction, clipboard paste, JavaScript to set a DOM value, or API/database setup to seed data. JavaScript may bypass input events and validation, so it should not be the default for user-flow testing.
Methods available in Alert
Switch using driver.switchTo().alert(). The common methods are accept(), dismiss(), getText(), and sendKeys() for prompt alerts. Use ExpectedConditions.alertIsPresent() to wait for an alert. Alert a = wait.until(ExpectedConditions.alertIsPresent());.
Click a button without click() or Enter
Use Actions to move to the target and perform a mouse click. JavaScript click is possible but bypasses normal interaction checks and should generally be a fallback. If the interviewer specifically prohibits WebElement.click() and Enter, Actions.click() is a suitable answer. new Actions(driver).moveToElement(button).click().perform();.
Interface vs abstract class
An interface defines a contract and a class can implement multiple interfaces. An abstract class can have constructors, instance fields, concrete methods, and abstract methods, but Java allows a class to extend only one class. Interfaces cannot have constructors or per-instance fields; they can have default, static, and private methods.
Launch a browser and go to Google
Create a WebDriver, call get(), and close the session in finally or test teardown. Selenium Manager in supported Selenium 4 versions can manage compatible drivers.
Estimate 100 test cases
Classify by complexity, stability, data/setup, automation feasibility, reusable components, browsers, integrations, and maintenance risk. Estimate analysis, coding, review, debugging, test data, CI, and stabilization separately. Provide assumptions and a range rather than estimating from count alone.
How many scripts can you automate per day?
There is no universal number. A simple stable test using existing page objects may be quick; a complex multi-page flow with OTP, file upload, database setup, or unstable UI may take much longer. Explain that you estimate by complexity, reuse, dependencies, data, and validation.
Why do you need a framework?
A framework provides reusable setup, conventions, utilities, configuration, reporting, and execution control. It reduces duplication and improves maintainability as the suite grows. Its complexity should be proportional to the suite; a throwaway script may not need a large framework.
Have you used Java Executor?
In Selenium interviews, this may mean JavascriptExecutor; clarify if needed. JavascriptExecutor executes JavaScript in the current page. java.util.concurrent.Executor is a different Java interface for executing tasks. JavascriptExecutor js = (JavascriptExecutor) driver; js.executeScript("window.scrollTo(0, document.body.scrollHeight);");.
Have you created an abstract class?
Answer based on your real project. A BaseTest may hold shared setup/teardown; an abstract base page may provide common behavior. Abstract classes are useful when shared state/implementation is needed, but composition and utility classes may be more suitable in other designs.
What are driver and By in driver.findElement(By.id(...))?
driver is a WebDriver reference representing the browser session. By is Selenium's locator factory class; By.id("username") describes how to locate an element. findElement returns the first matching WebElement or throws NoSuchElementException if none exists.
Which IDE and how do you get JAR files?
Common IDEs include Eclipse and IntelliJ IDEA. In a Maven project, add dependencies to pom.xml and run Maven Update Project in Eclipse; Maven resolves the JARs. Manually adding JARs to the build path is possible but makes version management harder.
Read Excel data and explain
Apache POI is a common choice for .xls and .xlsx. Open the workbook, select a sheet, iterate rows/cells, and close resources. DataFormatter reads cell values as displayed text; handle formulas and blank cells according to the requirement. try (InputStream in = new FileInputStream("testdata.xlsx"); Workbook wb = WorkbookFactory.create(in)) { Sheet sh = wb.getSheet("LoginData"); DataFormatter f = new DataFormatter();.
Framework folder structure
One common Maven layout: src/test/java contains tests, pages, step definitions, hooks, utilities, and listeners; src/test/resources contains feature files, configuration, and test data; pom.xml contains dependencies/plugins. Reports and logs are generated artifacts and often excluded from source control. project/ pom.xml src/test/java/{tests,pages,steps,hooks,utilities,listeners} src/test/resources/{features,config,testdata} reports/ (generated).
Get all links in a web table
Locate the table first and then find anchors within it. Iterate through the returned list and read text and href; scope to the table to avoid collecting unrelated page links.
Explain OOP concepts with real-time examples
Encapsulation bundles state and controls access (private bank balance); abstraction exposes essential behavior (Payment.pay()); inheritance extends behavior (Tester extends Employee); polymorphism allows different implementations behind one contract (CardPayment/UpiPayment).
Selenium login script with coding standards
Use meaningful names, stable locators, explicit waits, assertions, environment-based credentials, and cleanup. In a real framework, move locators/actions to LoginPage and browser lifecycle to a driver factory/base class. The code below is illustrative; add imports and configuration for your project. @BeforeMethod public void setUp() { driver = new ChromeDriver();.
Rerun failed cases from 200 TestNG tests
TestNG normally creates test-output/testng-failed.xml after a run with failed tests. Run that XML to rerun failed methods, subject to your runner configuration. If the suite must retry during the same run, use IRetryAnalyzer carefully for transient failures; retries should not hide real defects. mvn test -DsuiteXmlFile=testng-failed.xml Java, Selenium & TestNG Interview Questions 1–100 · Saravana Tech.
Get failed method name from ITestResult
ITestResult provides the invoked test method, status, parameters, and throwable. A listener can call getMethod().getMethodName() to record the method name. Use TestNG retry/listener mechanisms rather than directly invoking a test method by string name. public void onTestFailure(ITestResult result) {.
Rerun all failed cases using testng-failed.xml
After the first execution, inspect the generated testng-failed.xml and run it as the suite input. Ensure the correct output directory and build tool configuration. This is distinct from automatically retrying a failure within the same run.
Design a framework from scratch
Start with application and test requirements, then design runner, driver factory, config, page objects, data readers, utilities, assertions, reporting/listeners, and CI. Build a small vertical slice, validate stability, then scale. Keep secrets outside source control and ensure test independence.
Design for a stable application with 100–200 tests
Prioritize stable, high-value regression cases and group them by business flow/risk. Identify shared components, data needs, browser coverage, run frequency, CI capacity, and maintenance owners. Choose a minimal architecture that supports repeatability, parallelism if required, reporting, and debugging without overengineering.
Explain your framework structure
Explain responsibilities by layer: tests describe scenarios; page objects encapsulate UI; driver factory/base test manages sessions; utilities handle waits/config/data; listeners/hooks capture outcomes; reporting generates evidence; Maven and CI build/run/publish. Use your actual folder names in the interview.
Is one ExtentReports initialization line enough?
No. Initialization creates/configures the report object, but you must create test entries, log steps/statuses, attach screenshots/errors as needed, call flush/finalize, and publish the report. For parallel execution, ensure test/report nodes are managed safely. Exact API depends on ExtentReports version.
Draw a block diagram of the framework
Requirements / Test Cases | TestNG / Cucumber Runner | Hooks / BaseTest / DriverFactory | Page Objects <--> Utilities / Config / Test Data | Selenium WebDriver | Browser / App | Assertions / Listeners | Reports + Logs + Screenshots + CI results.
Excel or other data sheets?
Explain the actual project source. Excel suits business-managed tabular data; CSV is lightweight for flat data; JSON suits nested/API payloads; properties/environment variables are suitable for configuration. Choose based on shape, ownership, readability, and secure handling.
Why List and not HashMap?
List is suitable when row order and repeated rows matter. HashMap maps unique keys to values and does not represent multiple repeated records naturally. LinkedHashMap preserves insertion order for one record. A useful spreadsheet structure is List<Map<String,String>>.
Identify which of two elements is underlined
Read computed CSS property text-decoration-line and check whether it includes underline. If the visual underline is inherited or created by a pseudo-element, inspect the DOM/CSS more deeply.
New window with two nested frames: get text from inner frame
Save original handle; click the link; wait for the new handle; switch to it; switch to frame 1 then frame 2; locate and read the text; switch to default content when finished.
How to close the second window?
After switching to the second window, call driver.close() to close that current window, then switch back to the original handle. Ensure the original window is still open.
Difference between quit and close
close() closes the current window/tab in the WebDriver session. quit() ends the session and closes all windows associated with that session. Neither should be expected to close unrelated browser windows manually opened outside the WebDriver session.
Will quit close manually opened browsers?
Normally no. quit() closes windows belonging to the WebDriver session it controls, not unrelated browser sessions the user opened manually. Keep test sessions isolated.
Selenium evolution from RC to WebDriver
Selenium RC used a server/proxy and JavaScript injection approach. WebDriver controls browsers through browser-specific drivers and later standardized around the W3C WebDriver protocol. Selenium 3 transitioned toward W3C; Selenium 4 completed it and improved Grid and added relative locators. RC is obsolete.
Why Maven and CI?
Maven manages dependencies, builds, and test execution from pom.xml. CI tools such as Jenkins, GitHub Actions, GitLab CI, Azure Pipelines, and Bitbucket Pipelines can checkout code, run mvn clean test, publish reports, and archive logs/screenshots. Use secure credentials and controlled test environments.
Does Maven look locally or on the Internet?
Maven checks the local repository first (usually ~/.m2/repository). If the artifact/version is absent, it tries configured remote repositories such as Maven Central, subject to network, mirrors, settings, and offline mode.
Page Object Model vs normal project model
Page Object Model is a design pattern: each logical page/component is represented by a class containing locators and actions, while tests describe workflows and assertions. A script-heavy project may place all locators/actions in test classes. POM centralizes UI details and improves reuse/maintenance. It is different from Maven's pom.xml.
Do I need objects for home, search, and results pages?
Creating a page object per logical page/component is common, but objects need not all be created eagerly. Create the page object when navigating to/interacting with that page. Methods may return the next page object after a transition.
Access search page without SearchPage object?
Yes, you can use driver.findElement directly, because Selenium does not require page objects. However, page-specific locators then leak into test code and maintenance becomes harder. POM is a design choice, not a technical prerequisite.
If home page is unavailable, can you move to later pages?
It depends on routing, authentication, and application state. A direct destination URL may work if the user is authorized; otherwise the application may redirect or fail if earlier actions establish required state. Verify actual business flow and preconditions.
Exceptions encountered in Selenium
Common exceptions: NoSuchElementException, StaleElementReferenceException, TimeoutException, ElementClickInterceptedException, ElementNotInteractableException, InvalidSelectorException, NoSuchFrameException, NoSuchWindowException, and UnhandledAlertException. Explain the cause and fix for one or two from your actual experience. Java, Selenium & TestNG Interview Questions 1–100 · Saravana Tech.
How do you handle exceptions?
Use explicit waits, stable locators, correct frame/window context, reacquire stale elements, and log useful context. Catch only exceptions where a valid fallback exists. Do not catch every exception and continue because the test may falsely pass.
Alert may or may not appear after click
Wait briefly for alertIsPresent. If it appears, read and accept/dismiss it; if no alert is a valid outcome, catch TimeoutException narrowly and continue.
Reverse Cognizant without reverse()
Loop from the last index to zero, append charAt(i) to StringBuilder, and print the result.
Cognizant
The input string is "Cognizant". In the reverse program above, it is the string being processed; its reverse is "tnazingoC".
Find String length
String.length() returns the number of UTF-16 code units; for ordinary English text this matches the familiar character count.
Loop from length-1 to 0
Use for (int i = value.length() - 1; i >= 0; i--). The last valid index is length-1, and index 0 is the first character.
Get character using charAt(i)
String.charAt(i) returns the UTF-16 char at zero-based index i. In a reverse loop, it returns characters from right to left.
Concatenate characters
Use StringBuilder.append(char) for efficient concatenation in a loop. Repeated + on immutable strings can create unnecessary intermediate objects.
Print reversed string
After building the StringBuilder, print it with System.out.println(builder). The result for Cognizant is tnazingoC.
Most repeated character in Cognizant
Every character in case-sensitive "Cognizant" appears once, so all characters tie for the highest frequency (1). For a general string, count characters with a Map and find the maximum count.
Least repeated character in Cognizant
Every character appears once, so every character ties for the least frequency too. For a general string, count characters and find the minimum count; clarify how spaces and case are handled.
Print diamond pattern
Print an upper pyramid then a mirrored lower pyramid. Row i uses n-i-1 spaces and 2*i+1 stars; then iterate backwards from n-2 to zero. Java, Selenium & TestNG Interview Questions 1–100 · Saravana Tech int n=4;.
Second-last uppercase C position in the given string
Search backward, count uppercase C occurrences, and stop at the second. Print both zero-based index and one-based position so the interviewer can see which convention is used.
Replace a/e/i/o/u with 1/2/3/4/5
Map a→1, e→2, i→3, o→4, u→5. This example is case-insensitive and preserves other characters.
Tell me about the framework used in your project
Use the answer to Question 1, then add a truthful project example: what the application does, your responsibilities, the tools actually used, one automation challenge, how failures are diagnosed, and a measurable result only if you can support it. Java, Selenium & TestNG Interview Questions 1–100 · Saravana Tech.
How to read data from Excel?
Use Apache POI for modern .xlsx and .xls files. Open the workbook with WorkbookFactory, select a sheet, iterate rows and cells, use DataFormatter where appropriate, and close resources with try-with-resources. See Question 45 for a complete example.
How to handle multiple windows?
Save the original handle, click the link, wait until the handle count increases, identify the new handle by set difference, switch to it, and return to the original when done. Do not assume getWindowHandles order.
TestNG annotations and their structure
Typical order: @BeforeSuite, @BeforeTest, @BeforeClass, @BeforeMethod, @Test, @AfterMethod, @AfterClass, @AfterTest, @AfterSuite. @BeforeGroups/@AfterGroups apply around selected groups. Actual ordering can be affected by inheritance, XML settings, dependencies, and group hooks.
How to ignore TestNG test cases?
Use @Test(enabled=false) to disable a method or exclude methods/groups in testng.xml. @Ignore is commonly associated with JUnit, not the usual TestNG mechanism. Distinguish disabled tests from skipped tests caused by failed dependencies.
Can an interface have a constructor?
No. An interface cannot be instantiated and has no constructor. Implementing classes have constructors.
Access private data members from outside a class
Prefer public methods/getters/setters or behavior methods that preserve invariants. Reflection may access private members in some situations but can be restricted by Java modules and is not the default design. Avoid breaking encapsulation solely for testing.
HashMap vs Hashtable
HashMap is generally unsynchronized and permits one null key and null values. Hashtable is a legacy synchronized map and rejects null keys/values. ConcurrentHashMap is often preferred for concurrent access; LinkedHashMap preserves insertion order. Java, Selenium & TestNG Interview Questions 1–100 · Saravana Tech.
How to rate Selenium and Java from 0 to 5?
Give a calibrated answer supported by examples. For example: “Selenium 4/5 because I can build/debug UI tests, handle waits, frames, windows, POM, and execution. Java 3/5 because I’m comfortable with OOP, collections, exceptions, strings, and test code, and I’m strengthening advanced topics.” Adjust the rating to your actual ability; be ready for a coding question.
findElement vs findElements and missing locator result
findElement returns the first match and throws NoSuchElementException if none is found. findElements returns a List<WebElement>; if there are no matches, it returns an empty list, not null. Invalid XPath/CSS syntax may throw InvalidSelectorException for either method.
ArrayList vs LinkedList
ArrayList uses a resizable array and gives O(1) average indexed access and fast iteration; middle insertions/removals shift elements. LinkedList uses linked nodes and indexed access is O(n); insert/remove is O(1) only once the node is located. ArrayList is usually faster in typical workloads due to locality and less per-element overhead.
Maven in Eclipse and exact pom.xml tags
Maven uses pom.xml. Main tags include project, modelVersion, groupId, artifactId, version, properties, dependencies/dependency, build/plugins/plugin, and optionally repositories, profiles, and dependencyManagement. Add dependencies and use Maven → Update Project in Eclipse. The following shows the exact dependency/plugin nesting; replace versions with compatible actual releases.
What is TestNG, and how is it integrated with Selenium and pom.xml?
TestNG is a Java test framework providing annotations, assertions, groups, parameters, DataProvider, listeners, dependencies, and parallel execution. Selenium WebDriver performs browser automation; TestNG orchestrates tests. Add selenium-java and testng dependencies to pom.xml; Maven resolves them and Surefire commonly runs TestNG tests during the test phase. A suite XML can select classes, parameters, and parallel settings.
What is the XPath relationship between table elements?
In an HTML table, <table> contains <thead>, <tbody>, and/or <tfoot>; <tbody> contains <tr> rows; each <tr> contains <td> data cells or <th> header cells. XPath axes express these relationships: child ( / ), descendant ( // ), parent ( .. ), ancestor, following-sibling, and preceding-sibling. EXAMPLE / INTERVIEW TIP Example: //tbody/tr containing a first-position td. //td.
What is the relationship between the first <td> and <tr>, and between the first
<td> and <tbody>? A <td> is a direct child of its row (<tr>); the row is a direct child of <tbody>. Therefore, <td> is a descendant (usually a grandchild) of <tbody>, not its direct child. Java, Selenium & TestNG Interview Questions – Part 2 · Saravana Tech CTS Selenium Interview Questions with Answers Part 2 (2026) | Saravana Tech 100 Questions with Elaborate Answers, Examples, and Interview Guidance | EXAMPLE / INTERVIEW TIP Examples: //tr/td row); //td.
Why can ArrayList be faster than LinkedList for indexed access?
ArrayList uses a resizable array, so get(index) is O(1) on average. LinkedList is a doubly linked list; get(index) must traverse nodes from an end, so indexed access is O(n). Insertion/removal in the middle can be O(1) for LinkedList only when the node/iterator position is already known; finding the position costs time. ArrayList often performs better due to memory locality.
What is the Page Object Model (POM) project structure and its benefits?
POM is a design pattern in which each page or major UI component has a class containing its locators and page actions. Test classes describe business scenarios and call page methods rather than embedding locators everywhere. EXAMPLE / INTERVIEW TIP Typical structure: src/main/java/pages (LoginPage, HomePage), src/main/java/utils (WaitUtil, ExcelUtil, ConfigReader), src/test/java/tests (LoginTest), src/test/resources (config.properties, test data, testng.xml), pom.xml. Benefits: reuse, separation of concerns, easier maintenance when UI changes, readable tests, and less duplication.
What is TestNG? Explain annotations and execution order.
TestNG is a Java testing framework supporting annotations, assertions, groups, dependencies, data providers, parameterization, parallel execution, and XML suite configuration. A common order is @BeforeSuite, @BeforeTest, @BeforeClass, @BeforeMethod, @Test, @AfterMethod, @AfterClass, @AfterTest, @AfterSuite. @BeforeGroups/@AfterGroups run around tests in specified groups;.
Which parameters run tests repeatedly? Explain thread-count,
threadPoolSize, invocationCount and maxInstances. Use @Test(invocationCount = n) to invoke one test method n times. Use @Test(threadPoolSize = n, invocationCount = m) to run those invocations concurrently using a pool; threadPoolSize is meaningful with invocationCount. In testng.xml, parallel="methods|tests|classes" and thread-count="n" control parallel Java, Selenium & TestNG Interview Questions – Part 2 · Saravana Tech execution. maxInstances is not a standard @Test parameter in core TestNG; it may belong to a custom runner, framework, or another tool, so verify the exact context.
Difference between dependsOnGroups and dependsOnMethods?
dependsOnMethods makes a test depend on one or more named test methods. dependsOnGroups makes it depend on all methods in the named group(s). If a dependency fails or is skipped, the dependent test is normally skipped unless configuration changes the behavior. EXAMPLE / INTERVIEW TIP Example: @Test(dependsOnMethods="login") depends on login(). @Test(dependsOnGroups="smoke") depends on tests belonging to the smoke group. Dependencies can make tests order-sensitive; independent tests are generally more maintainable.
Difference between priority and dependsOnMethods, with example.
priority orders otherwise eligible test methods; lower numeric values run first by default. dependsOnMethods expresses a prerequisite and controls whether a test is eligible to run based on another method's result. Priority is ordering, not a success dependency. EXAMPLE / INTERVIEW TIP Example: @Test(priority=0) void login() {} and @Test(priority=1) void search() {} orders login before search. For a real prerequisite use @Test(dependsOnMethods="login") on search.
If a test has priority=0 and dependsOnMethods=method1, which runs first?
The dependency is the controlling constraint. TestNG must execute method1 before the dependent test can run, regardless of the dependent test's priority. Priority can order tests only when dependency constraints allow it. EXAMPLE / INTERVIEW TIP Example: @Test(priority=0, dependsOnMethods="method1") void method2() {} cannot run before method1.
How would you automate a personal-information page with a Submit
button? Identify stable locators for each field, populate valid test data, verify entered values, click Submit, and assert the expected next-page state. Prefer IDs, accessible labels, data-testid, or robust relative XPath/CSS over brittle absolute XPath. Java, Selenium & TestNG Interview Questions – Part 2 · Saravana Tech EXAMPLE / INTERVIEW TIP Example (Java): driver.findElement(By.id("firstName")).sendKeys("Asha");.
Submit opens a page with Sign in; clicking it shows username and
password labels. How do you automate it? Wait for the next page or navigation, locate and click Sign in, then wait for the username and password fields to become visible. Assert their visibility and optionally verify the labels/text.
Write a relative XPath when there are no IDs, names, or values.
Inspect the DOM and anchor the XPath to stable structure, visible text, labels, attributes, or nearby unique elements. Relative XPath starts from a relevant node, commonly with //, rather than the full document path. EXAMPLE / INTERVIEW TIP Examples: //label.
Write TestNG annotations in execution order.
Typical successful flow: @BeforeSuite → @BeforeTest → @BeforeClass → @BeforeMethod → @Test → @AfterMethod → @AfterClass → @AfterTest → @AfterSuite. Group configuration methods run around relevant group tests. With multiple test methods, BeforeMethod/AfterMethod run around each method. EXAMPLE / INTERVIEW TIP This is the common lifecycle order for a single class in one test context; suite XML, inheritance, groups, data providers, parallel execution, and failures can change the observed sequence.
If @Test is removed, what exception occurs?
Usually, TestNG simply does not recognize that method as a test method. It does not necessarily throw an exception; the method may not execute as a test, and the run may report zero tests or no tests to run depending on configuration and other tests. Java, Selenium & TestNG Interview Questions – Part 2 · Saravana Tech EXAMPLE / INTERVIEW TIP If another test depends on that method by name, TestNG may report a dependency configuration error or fail to resolve the dependency, depending on version and setup. Exact behavior depends on the test suite.
What is the POM in Maven? What is SNAPSHOT?
pom.xml (Project Object Model) describes a Maven project: groupId, artifactId, version, dependencies, plugins, properties, repositories, and build configuration. A version ending in -SNAPSHOT denotes development work that can change before a formal release; repositories may update it as newer snapshots are published. EXAMPLE / INTERVIEW TIP Example: <groupId>com.example</groupId>, <artifactId>ui-tests</artifactId>, <version>1.0- SNAPSHOT</version>. Release versions should be stable and immutable according to repository policy.
Difference between findElement and findElements.
findElement returns the first matching WebElement and throws NoSuchElementException if no match is found. findElements returns a List<WebElement>; it returns an empty list if there are no matches and does not throw just because none are found. EXAMPLE / INTERVIEW TIP Example: WebElement button = driver.findElement(By.id("submit")); List<WebElement> rows =.
How do you get the value/text of underlined text inside a frame?
Switch to the correct frame, locate the element, and read getText() for visible text or getAttribute("value") for a form control. Then switch back to default content when finished. EXAMPLE / INTERVIEW TIP Example: driver.switchTo().frame(driver.findElement(By.cssSelector("iframe"))); String text=driver.findElement(By.xpath("//u")).getText(); driver.switchTo().defaultContent();. Use the frame's id/name or a WebElement locator as appropriate.
What are Maven and Jenkins? Why use Maven?
Maven manages Java builds and dependencies using pom.xml and a standard lifecycle such as validate, compile, test, package, verify, install, and deploy. Jenkins is a CI/CD automation server that can check out source code, run Maven commands, publish reports, and notify teams. EXAMPLE / INTERVIEW TIP Typical pipeline: checkout Git → mvn clean test → publish TestNG/Surefire reports → archive artifacts. Maven standardizes builds; Jenkins automates them repeatedly on commits or schedules.
Write code to read Excel data using TestNG DataProvider.
Use Apache POI to read workbook cells and return a two-dimensional Object array from a @DataProvider. Close workbook/input stream and handle file paths reliably. EXAMPLE / INTERVIEW TIP Example: @DataProvider(name="loginData") public Object[][] data() throws Exception { try (FileInputStream in=new FileInputStream("src/test/resources/data.xlsx"); Workbook wb=WorkbookFactory.create(in)) { Sheet s=wb.getSheet("Login"); int rows=s.getLastRowNum(); Object[][] out=new Object.
What is settings.xml in Maven?
Maven settings.xml contains user/environment-specific configuration, commonly credentials or server IDs, mirrors, proxies, profiles, and repository settings. It is usually located at ~/.m2/settings.xml or supplied via -s path/to/settings.xml. EXAMPLE / INTERVIEW TIP It is different from pom.xml: pom.xml is project configuration that is generally checked into source control; settings.xml is usually local or CI environment configuration. Never commit plaintext credentials.
How does TestNG work with Maven groupId and version in pom.xml?
Maven resolves TestNG as a dependency from its coordinates: groupId, artifactId, and version. Maven Surefire Plugin can discover and run TestNG tests during the test phase, often using testng.xml for suite configuration. EXAMPLE / INTERVIEW TIP Example dependency: org.testng:testng:7.x.x with scope test. Configure maven-surefire-plugin and optionally <suiteXmlFiles><suiteXmlFile>testng.xml</suiteXmlFile></suiteXmlFiles>.
What is artifactId?
artifactId is the name of a Maven artifact within a groupId. Together with groupId and version, it identifies a dependency or build output. The packaged artifact often has a filename like artifactId-version.jar. EXAMPLE / INTERVIEW TIP Example: com.example:automation-tests:1.0-SNAPSHOT. groupId identifies the organization/project namespace; artifactId identifies the particular module; version identifies its release.
Tech Round 1: how should you prepare?
Treat this as a round label rather than a technical question. Prepare a concise project summary, Java fundamentals, Selenium locators/waits/frames/windows, TestNG lifecycle and dependencies, Maven, reporting, CI, SQL/API basics, and one real debugging story. EXAMPLE / INTERVIEW TIP For each topic, explain the definition, why it matters, a small example, and how you used it. If asked to code, state assumptions and write compilable core logic.
Tell me about your project.
Use a 60–90 second structure: business purpose, application/domain, your role, team/process, tools, automation architecture, test scope, CI/reporting, and measurable outcome. Do not disclose confidential information. EXAMPLE / INTERVIEW TIP Template: “I work on a requirement analysis, test planning, automation design, reviews, defect triage, and release reporting. Our stack includes execution.
Explain static, final, abstract, interface, and exception handling in Java.
static belongs to the class rather than an instance. final prevents reassignment of a variable, overriding of a method, or inheritance from a class. abstract classes can contain abstract and concrete methods and cannot be instantiated. Interfaces define a contract and can have abstract, default, static, and (newer Java) private methods. Exception handling uses try/catch/finally, throw, and throws. EXAMPLE / INTERVIEW TIP Example: final int max=10; static int count; abstract class Shape { abstract double area(); } interface Login { void signIn(); } try { ... } catch (IOException e) { ... } finally { ... }.
Explain frame handling, window handling, and Excel read/write in Selenium.
For frames, switch using frame name/id, index, or WebElement and return with defaultContent()/parentFrame(). For windows, capture driver.getWindowHandles(), switch to the target handle, and close only the intended window. Use Apache POI for Excel read/write. EXAMPLE / INTERVIEW TIP Frame: driver.switchTo().frame("paymentFrame"); ...; driver.switchTo().defaultContent().
How have you implemented automation in your project?
Explain the process: analyze requirements and identify repeatable/high-value scenarios; select a tool; build reusable driver, page, wait, data, and reporting layers; implement assertions; manage data and environments; integrate with CI; review failures and maintain scripts. EXAMPLE / INTERVIEW TIP A credible example: automate smoke/regression flows with Selenium Java, POM, TestNG, Maven, and a reporting library; use explicit waits, stable locators, data-driven tests, Git reviews, and Jenkins runs.
Explain your framework in detail.
Describe layers: test/scenario layer, page objects, reusable utilities, driver/browser factory, configuration, test data, assertions, logging/reporting, build/dependency management, and CI. Explain how data flows from test to page object to application and how failures are captured. EXAMPLE / INTERVIEW TIP A common layout: src/test/java/tests, src/main/java/pages, utils, driver, listeners; src/test/resources/testdata and config; pom.xml; testng.xml; reports. Explain parallel safety, environment selection, secret handling, retries (if used), and test isolation.
What difficulties did you face and how did you overcome them?
Choose a real example and answer with Situation, Task, Action, Result. Good technical examples include flaky dynamic elements, stale elements, unstable test data, asynchronous API/UI behavior, environment instability, or long execution time. EXAMPLE / INTERVIEW TIP Example structure: “A dynamic table caused intermittent failures. I reproduced the issue, inspected DOM timing, replaced fixed sleeps with explicit waits, improved the locator, and added diagnostic screenshots/logs.
How did you report automation results?
Describe the reporting tool and the information captured: passed/failed/skipped tests, duration, stack traces, screenshots, browser/environment, build number, and links to logs. Explain how reports are shared and how failures are triaged. EXAMPLE / INTERVIEW TIP TestNG with Maven Surefire produces XML/text reports under target/surefire-reports by default. ExtentReports or Allure can provide richer HTML reports if configured.
Tell me about yourself, why leave, and why join CTS?
Keep each answer concise, positive, and specific. Introduce experience, current role, relevant skills, leadership, and target role. For switching, focus on growth, broader responsibilities, technical challenges, or role alignment; avoid criticizing your current employer. For CTS/Cognizant, connect your skills to the job description and the role's domain.
Nothing was asked outside what we learned in two months—what does this
mean? This is a candidate's observation, not a technical question. It means interview preparation covering the stated fundamentals was sufficient for that particular interview; it does not guarantee other interviewers will ask the same topics. EXAMPLE / INTERVIEW TIP Prioritize understanding and practical exercises over memorizing answers.
What are implicit wait and explicit wait?
Implicit wait tells WebDriver to poll when locating elements for a configured duration. Explicit wait waits for a specific condition, such as visibility or clickability, using WebDriverWait and ExpectedConditions. Avoid mixing implicit and explicit waits because combined timing can be unpredictable. EXAMPLE / INTERVIEW TIP Example: driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(5)); Explicit: new WebDriverWait(driver, Duration.ofSeconds(10)).until(ExpectedConditions.elementToBeClickable(By.id("submit"))).click(); Prefer explicit waits for dynamic UI conditions.
Write code to launch Google.
Create a WebDriver, navigate to the URL, and close the browser after the test. Ensure the correct browser driver is available or use Selenium Manager in modern Selenium versions. EXAMPLE / INTERVIEW TIP Example: WebDriver driver = new ChromeDriver(); try { driver.get("https://www.google.com");.
Write syntax for relative XPath.
A relative XPath starts from anywhere in the document using // or from a known node. It is generally less brittle than an absolute path such as /html/body/div/... . EXAMPLE / INTERVIEW TIP Examples: //input.
Write XPath for visible text.
Use text() or normalize-space() to match element text. Exact text: //button Partial text: //a EXAMPLE / INTERVIEW TIP For nested text, normalize-space(.) is often more robust than text() because it includes descendant text. Avoid matching generic text if it appears in multiple elements; scope it to a unique container.
How do you achieve a Data-Driven Framework?
Separate test logic from test data. Supply multiple data sets through TestNG @DataProvider, CSV/Excel/JSON/DB, or configuration files. Reuse the same test method for each data row and report each invocation clearly. EXAMPLE / INTERVIEW TIP Example: @Test(dataProvider="users") void login(String username,String password){...}.
What is POM?
POM means Page Object Model in Selenium: a class represents a page/component, owns locators, and exposes actions such as login() or search(). Test classes call these actions and assert outcomes. EXAMPLE / INTERVIEW TIP Example: LoginPage has username, password, and submit locators plus enterUsername(), enterPassword(), and clickLogin(). Keep business assertions mostly in tests or clearly designed page/component methods.
What is TestNG?
TestNG is a Java testing framework inspired by JUnit and designed for flexible test configuration. It provides annotations, assertions, grouping, dependencies, data providers, parameterization, listeners, and parallel execution. Java, Selenium & TestNG Interview Questions – Part 2 · Saravana Tech EXAMPLE / INTERVIEW TIP It integrates with Maven through a TestNG dependency and Surefire plugin, and can run suites from testng.xml. It is commonly used for Selenium UI automation.
Difference between @BeforeTest and @BeforeMethod.
@BeforeTest runs once before test methods belonging to a <test> element in testng.xml. @BeforeMethod runs before each @Test method invocation, including data-provider invocations. EXAMPLE / INTERVIEW TIP Use @BeforeTest for setup shared by a test XML section (when appropriate); use @BeforeMethod for per-test setup such as creating a fresh driver or resetting state. Pair with @AfterTest/@AfterMethod.
What is a collection? Explain List and Set.
The Java Collections Framework provides interfaces and implementations for groups of objects. List is ordered and permits duplicates; Set represents unique elements and may or may not guarantee iteration order depending on implementation. EXAMPLE / INTERVIEW TIP Examples: ArrayList for ordered indexed data; LinkedList for list/deque operations; HashSet for uniqueness without guaranteed order; LinkedHashSet for insertion order; TreeSet for sorted order. Use generics such as List<String>.
What are DesiredCapabilities?
DesiredCapabilities historically represented requested browser/platform capabilities for Selenium Grid or remote sessions. Modern Selenium uses browser-specific Options classes such as ChromeOptions, FirefoxOptions, and EdgeOptions, which implement capabilities. EXAMPLE / INTERVIEW TIP Example: ChromeOptions options = new ChromeOptions(); options.addArguments("--headless=new");.
There are 100 table rows, each with three td values. How do you check
duplicate names in 20 rows? Collect the name column from each row and count occurrences using a Map, or compare the number of values with a Set. If the name is in the second column, extract cell index 1 from each row; adapt to the actual table. Java, Selenium & TestNG Interview Questions – Part 2 · Saravana Tech EXAMPLE / INTERVIEW TIP Example: List<WebElement> rows=driver.findElements(By.cssSelector("tbody tr")); Map<String,Integer> counts=new HashMap<>(); for(WebElement row:rows){ List<WebElement> cells=row.findElements(By.tagName("td")); if(cells.size()>1){String name=cells.get(1).getText().trim(); counts.merge(name,1,Integer::sum);} } counts.forEach((name,count)->{if(count>1).
How do you check duplicate name values in a table?
Read the name column, normalize whitespace/case if the business rule says values are case-insensitive, and count values. A HashSet can detect whether a duplicate has appeared; a Map gives counts. EXAMPLE / INTERVIEW TIP Set approach: if (!seen.add(name)) System.out.println("Duplicate: "+name). Ignore blank names if required.
Difference between List and Set.
List preserves sequence and permits duplicate values; it supports index-based access. Set prevents duplicate elements and has no index-based get method. Ordering depends on implementation. EXAMPLE / INTERVIEW TIP ArrayList is a List; HashSet is a Set; LinkedHashSet preserves insertion order; TreeSet sorts according to natural order/comparator.
What is an interface in Java?
An interface defines a contract that implementing classes agree to provide. It supports abstraction and allows a class to implement multiple interfaces. Interfaces can contain constants, abstract methods, and default/static methods; newer Java also supports private helper methods. EXAMPLE / INTERVIEW TIP Example: interface Payment { void pay(double amount); } class CardPayment implements Payment { public void pay(double amount){...} }.
Difference between abstract class and interface.
An abstract class can hold instance state, constructors, and both abstract and concrete methods; a class can extend only one class. An interface defines a contract and a class can implement multiple interfaces; interfaces do not have ordinary per-instance fields. Java, Selenium & TestNG Interview Questions – Part 2 · Saravana Tech EXAMPLE / INTERVIEW TIP Use an abstract class for closely related classes sharing state or implementation. Use an interface for a capability/contract across potentially unrelated classes.
Why is multiple inheritance of classes not supported in Java?
Java disallows extending multiple classes mainly to avoid ambiguity and complexity such as the diamond problem when parent classes define the same method or state. Java supports multiple inheritance of type through interfaces. EXAMPLE / INTERVIEW TIP Example: class C cannot extend A, B, but can implement AContract, BContract. If two interfaces provide conflicting default methods, the implementing class must resolve the conflict explicitly.
Explain your framework.
Explain the framework's architecture, folder structure, design pattern, driver lifecycle, locator strategy, waits, data management, assertions, reporting, configuration, logging, CI, and how it scales. Mention only components you really use. EXAMPLE / INTERVIEW TIP Use a concrete flow: test reads data → page object performs actions → utility waits for state → assertion validates result → listener/report captures status → CI publishes report. Be ready to show a real test and trace it through layers.
How do you execute groups in TestNG?
Assign groups using @Test(groups={"smoke"}) and include/exclude them in testng.xml, or configure Maven Surefire group filters. Groups support suites such as smoke, regression, and integration. EXAMPLE / INTERVIEW TIP Example XML: <groups><run><include name="smoke"/></run></groups>. Ensure testng.xml is connected to the Maven Surefire configuration if Maven is the execution entry point.
Explain your framework (repeated question).
Give a consistent, concise version of your framework explanation rather than a different story. Cover architecture, reusable components, test data, reporting, CI, and one design decision. EXAMPLE / INTERVIEW TIP Prepare a 2-minute explanation and a simple diagram: Test layer → Page objects → Selenium/WebDriver → application; shared utilities/config/data and reporting surround the flow. Java, Selenium & TestNG Interview Questions – Part 2 · Saravana Tech.
How is data-driven testing achieved?
Provide different input sets to the same test logic through a data provider or external data source. The test method accepts parameters and executes once per data row. EXAMPLE / INTERVIEW TIP TestNG @DataProvider is common. External data can come from Excel via Apache POI, JSON, CSV, or databases.
What are class and package?
A class is a blueprint that defines fields, constructors, and methods for objects. A package groups related types, helps organize code, and provides a namespace/access boundary. EXAMPLE / INTERVIEW TIP Example: package com.company.pages; public class LoginPage { ... }. The fully qualified name is com.company.pages.LoginPage.
List packages used in Selenium projects.
Common Java imports include org.openqa.selenium.*, org.openqa.selenium.chrome.ChromeDriver, org.openqa.selenium.support.ui.WebDriverWait, org.openqa.selenium.support.ui.ExpectedConditions, org.openqa.selenium.interactions.Actions, org.openqa.selenium.support.ui.Select, and org.testng.annotations.*. EXAMPLE / INTERVIEW TIP Utilities may use java.time.Duration, java.util.List/Map, java.io, Apache POI packages such as org.apache.poi.ss.usermodel.*, and logging/reporting libraries. Name only those actually used in your project.
What are class and object?
A class defines the structure/behavior; an object is a runtime instance of that class. Objects have state (fields) and behavior (methods). EXAMPLE / INTERVIEW TIP Example: class Car { String model; void start(){...} } then Car c = new Car(); c.model="Sedan"; c.start();. A reference variable holds a reference to an object, not the object itself.
Can static variables or methods be overridden?
Static methods are hidden, not overridden, because they belong to the class and method selection is based on the reference/class type. Static variables are also hidden, not overridden. Instance methods can be overridden subject to access and signature rules. Java, Selenium & TestNG Interview Questions – Part 2 · Saravana Tech EXAMPLE / INTERVIEW TIP Example: class A { static void show(){} } class B extends A { static void show(){} } is method hiding.
Answer questions about your project.
Prepare the business goal, users, system components, integrations, test environments, release cadence, your ownership, team size, test strategy, automation coverage, defects, and results. Avoid confidential customer data. EXAMPLE / INTERVIEW TIP Use real examples: a critical end-to-end flow, a defect caught before release, a flaky test you stabilized, or a CI improvement. Explain what you personally did versus what the team did.
Tell me about yourself.
Deliver a tailored 60–90 second introduction: experience, current role, core skills, domain, leadership, achievements, and target role. Do not recite every tool or personal detail. EXAMPLE / INTERVIEW TIP Template: “I’m a QA professional with current role I handle framework maintenance, defect analysis, and delivery coordination. I’m now looking for apply this experience and grow in.
Rate yourself in Java and Selenium out of 5.
Give an honest rating and justify it with examples. A rating of 4/5 can communicate strong practical experience while acknowledging areas to improve; do not choose a number just to impress. EXAMPLE / INTERVIEW TIP Example: “Java 4/5 and Selenium 4/5. I can build and maintain automation, work with collections/OOP, handle waits/frames/windows, and debug failures.
Explain your project architecture.
Describe application layers and testing architecture: UI/API/services/data stores, environments, automation layers, test data, build pipeline, and reporting. Explain which parts your tests cover and how they integrate. EXAMPLE / INTERVIEW TIP A generic automation architecture is tests → page objects/API clients → utilities/config/data → application; Maven builds; TestNG executes; Jenkins triggers; reports/logs are published. Adapt it to your actual system.
Explain the design pattern for a login page.
Use Page Object Model: LoginPage encapsulates username/password locators and login actions; LoginTest provides test data and verifies the outcome. Avoid exposing implementation details unnecessarily. EXAMPLE / INTERVIEW TIP Java sketch: class LoginPage { private WebDriver driver; private By username=By.id("username"); private By password=By.id("password"); private By signIn=By.id("signIn"); LoginPage(WebDriver d){driver=d;} HomePage login(String u,String p){driver.findElement(username).sendKeys(u);.
Write a wrapper click method that works with a String and a WebElement.
Overload a utility method: one overload accepts a locator string and resolves it; another accepts a WebElement. Prefer By locators over arbitrary XPath strings when possible, and avoid swallowing exceptions. EXAMPLE / INTERVIEW TIP Example: void click(By by){ wait.until(ExpectedConditions.elementToBeClickable(by)).click(); } void click(WebElement element){ wait.until(ExpectedConditions.elementToBeClickable(element)).click(); }. If the requirement literally specifies String, define click(String xpath){ click(By.xpath(xpath)); }.
What is an object repository?
An object repository stores UI element locators separately from test logic, commonly in page-object fields, properties files, or a locator map. This centralizes locator maintenance. EXAMPLE / INTERVIEW TIP POM classes often act as a structured object repository. For example, By loginButton=By.id("login").
A list of 10 elements shares id=xyz. Get and print all text.
Use findElements, because an ID should ideally be unique in HTML but the locator can still return multiple matches. Iterate over the returned list and print each element's text. EXAMPLE / INTERVIEW TIP Example: List<WebElement> items=driver.findElements(By.id("xyz")); for(WebElement item:items) {System.out.println(item.getText());}. If the markup uses repeated elements, a class or data attribute is more appropriate than duplicate IDs.
From those elements, select only the fifth and check whether it is a String.
The fifth element is at index 4 because Java collections are zero-based. getText() returns a String, so you can assign it to String or check with instanceof if the value is held as Object. EXAMPLE / INTERVIEW TIP Example: List<WebElement> items=driver.findElements(By.id("xyz")); if(items.size()>=5){ String text=items.get(4).getText(); System.out.println(text instanceof String); } else { System.out.println("Fewer than five elements"); }. If the question means checking a variable's runtime type, use Object value=text; value instanceof String.
What locators have you used in Selenium?
Selenium's classic By strategies include id, name, className, tagName, linkText, partialLinkText, cssSelector, and xpath. Newer Selenium also supports relative locators such as above/below/near for suitable cases. EXAMPLE / INTERVIEW TIP Prefer stable unique IDs or test attributes; use CSS or XPath when needed. Avoid brittle absolute XPath, dynamic indexes, and duplicate-ID assumptions.
What is relative XPath and how many types of XPath are there?
Relative XPath starts from a matching node anywhere in the document, commonly using //. Absolute XPath starts at the document root using a path such as /html/body/... and is typically more brittle. There is no universal fixed count of XPath “types”; interviewers often mean absolute versus relative XPath, or XPath axes/functions. EXAMPLE / INTERVIEW TIP Examples: //input Axes include parent, child, ancestor, descendant, following-sibling, preceding-sibling, following, preceding, and self.
What is an annotation in TestNG?
An annotation is metadata written with @ that tells TestNG how to treat a method or class. Examples include @Test, @BeforeMethod, @AfterMethod, @DataProvider, @Parameters, and @Listeners. EXAMPLE / INTERVIEW TIP Annotations reduce XML/boilerplate and define lifecycle, test grouping, data supply, dependencies, and configuration. The Java compiler and TestNG interpret annotations according to their definitions.
How many TestNG annotations are there?
There is no single stable count across every TestNG version because annotations and features can evolve. Common core lifecycle annotations are @BeforeSuite, @AfterSuite, @BeforeTest, @AfterTest, @BeforeClass, @AfterClass, @BeforeMethod, and @AfterMethod. Other common annotations include.
A subclass extends a superclass with four methods—what happens?
The subclass inherits accessible superclass methods unless they are overridden or hidden. The exact output cannot be determined without the actual method signatures, access modifiers, and calls. EXAMPLE / INTERVIEW TIP If the superclass has four public/protected instance methods and the subclass adds none, an instance of the subclass can generally call those inherited methods. Private methods are not inherited as accessible members; constructors are not inherited.
And in the superclass…
The question is incomplete without the superclass code. In general, superclass fields, constructors, static methods, and instance methods follow different inheritance/initialization rules. Provide the exact snippet to determine exact output. EXAMPLE / INTERVIEW TIP When tracing output, check static initialization, instance initialization, constructor chaining via super(), overridden-method dispatch, field hiding, and method overloading.
What will be the output of the above code?
The referenced code is not included in the question list, so the exact output cannot be determined safely. Do not guess in an interview; ask to see the full snippet. EXAMPLE / INTERVIEW TIP Trace statements in execution order, including static blocks first, then object initialization and constructors, then method calls. For overridden instance methods, runtime object type determines dispatch; static methods and fields are resolved by reference/class type.
What is Selenium Grid and how do you implement it?
Selenium Grid runs WebDriver tests on remote machines/browsers and supports parallel execution across browser and OS combinations. Modern Grid commonly uses a standalone server or distributed components such as Router, Distributor, Session Map, and Nodes. Java, Selenium & TestNG Interview Questions – Part 2 · Saravana Tech EXAMPLE / INTERVIEW TIP Start Grid (for example, a compatible Selenium Server standalone JAR), register or configure nodes as needed, then create RemoteWebDriver with the Grid URL and browser Options. In CI, distribute tests carefully and isolate test data.
How is Jenkins useful?
Jenkins automates repeatable CI jobs: checkout, build, test, report publication, artifact archiving, notifications, and scheduled/nightly runs. It can trigger after commits or on a schedule. EXAMPLE / INTERVIEW TIP Example pipeline stage: sh 'mvn clean test'. Configure credentials securely, select JDK/Maven, publish Surefire or HTML reports, and archive logs/screenshots.
Explain keyword-driven testing.
In keyword-driven testing, test steps are represented by keywords such as OPEN_BROWSER, ENTER_TEXT, CLICK, and VERIFY_TEXT. A driver/engine maps each keyword to reusable code; test cases and data can be maintained in a spreadsheet or external file. EXAMPLE / INTERVIEW TIP Benefits include reuse and easier authoring for non-programmers; drawbacks include designing and maintaining a generic keyword engine and debugging indirection. It can be combined with data-driven testing and POM.
What is Maven and how have you implemented it?
Maven is a build and dependency management tool. A pom.xml defines project coordinates, dependencies, plugins, properties, and build lifecycle. In a test project, it resolves Selenium/TestNG/POI dependencies and runs tests through Surefire. EXAMPLE / INTERVIEW TIP Typical command: mvn clean test.
How does testng.xml work?
testng.xml defines a suite and one or more <test> sections, with classes/packages, groups, parameters, listeners, and parallel settings. It lets a team select and configure a test run without editing source code. EXAMPLE / INTERVIEW TIP Example: <suite name="Regression"><test name="UI"><classes><class name="tests.LoginTest"/> </classes></test></suite>. Configure Maven Surefire to use the file if tests are launched via Maven.
How do you run a suite level in XML?
Create testng.xml with a <suite> root and include classes or packages under one or more <test> elements. Run it from the IDE as a TestNG suite or configure Maven Surefire to point to the suite file. EXAMPLE / INTERVIEW TIP Example Maven configuration uses <suiteXmlFiles><suiteXmlFile>testng.xml</suiteXmlFile> </suiteXmlFiles>. A command-line invocation can also run TestNG directly with the suite file, depending on project setup.
What is an exception?
An exception is an event that disrupts normal program flow. Java exceptions are objects. Checked exceptions must be caught or declared; unchecked exceptions (RuntimeException and its subclasses) generally indicate programming or runtime conditions. EXAMPLE / INTERVIEW TIP Use try/catch to handle recoverable cases, finally or try-with-resources to release resources, throw to raise an exception, and throws to declare possible exceptions.
What will happen in the above code?
The code referred to is not included, so the exact result cannot be established. To answer accurately, review the complete code and any relevant inputs. EXAMPLE / INTERVIEW TIP Check control flow, variable initialization, exception paths, loop conditions, object state, and whether the exception is caught or propagated. Share the snippet to get an exact output trace.
What happens if a WebElement is not found?
findElement throws NoSuchElementException if no matching element is found at lookup time. With an implicit wait, it retries locating until the timeout expires. findElements returns an empty list instead. EXAMPLE / INTERVIEW TIP For dynamic pages, wait for the expected condition and check locator correctness. Do not catch and ignore the exception unless there is a meaningful recovery path.
When does an exception occur and when does else execute?
Java has no general try/except/else construct. In Java, catch executes when a matching exception is thrown in the try block; finally normally executes whether an exception occurs or not. An else block is a feature of languages such as Python, not Java exception syntax. Java, Selenium & TestNG Interview Questions – Part 2 · Saravana Tech EXAMPLE / INTERVIEW TIP If the interviewer shows pseudocode with else, clarify the language.
What exceptions have you faced in a project? Explain try/catch.
Common Selenium exceptions include NoSuchElementException, TimeoutException, StaleElementReferenceException, ElementClickInterceptedException, ElementNotInteractableException, and NoSuchFrameException. Mention only those you actually encountered and explain the cause and fix. EXAMPLE / INTERVIEW TIP Example: catch TimeoutException to capture screenshot/logs and fail the test with context. Use explicit waits for expected state, refresh stale locators by re-finding elements, and fix overlays/interception rather than blindly retrying.
What is SoapUI and service testing?
SoapUI is a tool for testing APIs and web services, especially SOAP and REST. Service testing validates request/response behavior, status codes, headers, payloads, schemas, authentication, negative cases, and integration rules without relying solely on the UI. EXAMPLE / INTERVIEW TIP For SOAP, inspect WSDL and XML envelopes; for REST, validate HTTP methods, status, JSON/XML payloads, headers, and error handling. Automate repeatable API checks and manage test data/environment carefully.
Where have you executed SQL in your project?
Describe the real use case, such as validating UI data against a database, checking test data, investigating defects, verifying batch/ETL outcomes, or confirming records after API operations. Name the database only if accurate. EXAMPLE / INTERVIEW TIP Example query: SELECT status, COUNT(*) FROM appointments GROUP BY status; or SELECT * FROM customer WHERE customer_id = ?. Use parameterized queries, least-privilege access, and non- production data according to policy.
What are function/method overloading and overriding?
Overloading uses the same method name with different parameter lists in the same class or hierarchy; it is resolved at compile time. Overriding redefines an inherited instance method with a compatible signature; runtime dispatch selects the implementation based on the object type. Java, Selenium & TestNG Interview Questions – Part 2 · Saravana Tech EXAMPLE / INTERVIEW TIP Overloading example: click(By by), click(WebElement e). Overriding example: class Animal { void speak() {} } class Dog extends Animal { @Override void speak(){} }.
Do you want to execute two or three tests and go home, or take challenges?
This is a behavioral question about ownership, learning, and accountability. Say that you value reliable delivery and are willing to take on challenges, while prioritizing risk and quality rather than equating long hours with commitment. EXAMPLE / INTERVIEW TIP Example: “I prefer taking ownership of meaningful quality challenges—improving coverage, stabilizing automation, investigating failures, and helping the team deliver. I also plan work realistically and communicate risks early.” Add a genuine example.
Do you know mobile automation?
Mobile automation tests native, hybrid, or mobile web apps. Appium is a widely used option that exposes WebDriver-style APIs and supports Android and iOS, subject to environment/tooling requirements. EXAMPLE / INTERVIEW TIP Explain capabilities, device/emulator setup, app package/activity or bundle ID, locators, waits, gestures, permissions, and device-farm execution. If your experience is theoretical, say so honestly rather than claiming hands-on production use.
Give a brief introduction about yourself.
Use the same focused introduction as question 58, tailored to the job description. State years of experience accurately, key tools, current responsibility, leadership contribution, and the next role you seek. EXAMPLE / INTERVIEW TIP Keep it under 90 seconds and finish with why your background fits the role. Avoid personal history unrelated to the job.
How have you implemented TestNG annotations in your project?
Explain setup/teardown, test methods, grouping, data providers, and listeners as used in your project. @BeforeMethod may initialize test state; @Test runs scenarios; @AfterMethod captures results/cleans up; listeners can capture failures and screenshots. EXAMPLE / INTERVIEW TIP Illustrative lifecycle: @BeforeClass creates shared configuration; @BeforeMethod starts a driver; @Test executes a scenario; @AfterMethod captures failure details and quits driver. Ensure driver lifecycle matches parallel execution and your framework design. Java, Selenium & TestNG Interview Questions – Part 2 · Saravana Tech.
Explain Maven projects and their importance.
Maven standardizes project structure and build lifecycle, manages transitive dependencies, makes builds repeatable, and integrates with CI. Developers use pom.xml to declare dependencies/plugins instead of manually managing JAR files. EXAMPLE / INTERVIEW TIP Mention commands such as mvn clean test, mvn package, and profiles if relevant. Version pinning and reproducible configuration reduce “works on my machine” issues.
Explain Jenkins and its implementation.
Describe a Jenkins job or pipeline that checks out code, selects the JDK/Maven runtime, runs tests, publishes results, archives artifacts, and notifies stakeholders. Explain triggers such as pull requests, commits, or nightly schedules. EXAMPLE / INTERVIEW TIP Keep credentials in Jenkins Credentials or a secret manager. Make reports and logs accessible; define failure thresholds and avoid marking a build successful when critical tests fail.
Explain wrapper classes and POM; how are they implemented in methods?
Wrapper classes (Integer, Double, Boolean, Character, etc.) represent primitive values as objects and support collections/generics, conversion, and utility methods. POM is the Page Object Model pattern for UI automation. They are separate concepts. EXAMPLE / INTERVIEW TIP Example wrapper: Integer count = Integer.valueOf("10"); int n=count; (autoboxing/unboxing).
How do you implement TestNG with POM?
Create page classes for UI actions and TestNG test classes for scenarios/assertions. Use TestNG annotations for setup/teardown, @DataProvider for test data, groups for suites, and listeners for reporting. Maven/Surefire runs the suite. EXAMPLE / INTERVIEW TIP Flow: LoginTest → LoginPage.login() → HomePage/expected state → TestNG assertion.
Where are reports stored in a Maven project?
Maven Surefire reports are typically stored under target/surefire-reports, including XML and text files. Other HTML reporting tools store reports in configured locations, such as target/site or a project-specific report folder. EXAMPLE / INTERVIEW TIP The exact path depends on plugin and framework configuration. Jenkins may archive or publish these reports elsewhere; mention the real path used by your project.
What are SoapUI and SoapUI Pro?
SoapUI is used for functional testing of SOAP and REST services. “SoapUI Pro” has historically referred to commercial/ReadyAPI capabilities, offering enhanced features such as data-driven testing, advanced reporting, and team-oriented workflows depending on product version/licensing. EXAMPLE / INTERVIEW TIP Focus on what your team actually used. Core service-testing concepts—requests, assertions, environments, authentication, data sources, and regression suites—matter more than product branding.
Explain Grid hub and node implementation and why use Grid.
In older Selenium Grid architecture, the Hub receives session requests and routes them to registered Nodes that provide browser slots. Grid 4 uses a more distributed architecture with components such as Router, Distributor, Session Map, Event Bus, and Nodes; standalone mode packages them together. EXAMPLE / INTERVIEW TIP Use Grid to run tests remotely and in parallel across browser/OS combinations. Configure browser capabilities, register nodes (for older Grid), point RemoteWebDriver to the Grid URL, and ensure tests/data are isolated.
Do you know mobile automation?
Answer honestly about hands-on experience. For Appium, describe the WebDriver-based model, Android/iOS setup, capabilities, device/emulator, app lifecycle, locators, gestures, and reporting. EXAMPLE / INTERVIEW TIP If you have not used it on a real project, say: “I understand the concepts and have studied Appium, but my primary hands-on automation has been web/API testing. I’m prepared to extend my experience.”.
Why do you want to switch companies?
Give a positive, forward-looking answer based on role scope, learning, ownership, technology, domain, or career growth. Avoid complaints about managers, colleagues, or compensation as the only reason. Java, Selenium & TestNG Interview Questions – Part 2 · Saravana Tech EXAMPLE / INTERVIEW TIP Example: “I’m grateful for what I’ve learned, and I’m looking for a role with broader QA ownership, opportunities to improve automation strategy, and alignment with my longer-term goals. This role appears to offer that through.
What is your total experience and relevant experience?
State total experience and relevant experience separately and accurately. Relevant experience should be broken down by the skills asked for, and the numbers should match your resume and employment dates. EXAMPLE / INTERVIEW TIP Template: “My total experience is Playwright, years unless you explain that skills were used concurrently. Java, Selenium & TestNG Interview Questions – Part 2 · Saravana Tech.
Tell me about yourself and relevant automation experience
Use a concise, truthful 60–90 second introduction: total experience, current role, testing scope, automation stack, leadership responsibilities, and one relevant result. Example template: “I have hands-on experience includes release reporting. I’m interested in this role because it aligns with my experience in experience consistent with your resume.
What is an IDE and what is it used for?
IDE means Integrated Development Environment. It combines a code editor, project explorer, build/run tools, debugger, refactoring support, and often version-control integration. Examples include IntelliJ IDEA, Eclipse, and Visual Studio Code. It helps create, compile, execute, debug, and maintain code more efficiently than using only a plain text editor.
Can you run your complete suite in an IDE?
Usually yes, if the IDE has the required JDK, dependencies, test framework plugin, configuration, environment access, and test data. In Eclipse/IntelliJ, you can run a TestNG XML suite or a test class; Maven projects can also run using Maven goals. Large suites may be better run through Maven/CI to match production-like settings and avoid IDE-specific configuration.
Can you directly reference ChromeDriver in a script? Will it work?
A Selenium script can instantiate ChromeDriver when Selenium and a compatible driver/browser setup are available. Modern Selenium versions include Selenium Manager, which can resolve/download a suitable driver in supported environments. Older setups required a chromedriver executable and sometimes System.setProperty("webdriver.chrome.driver", "path"). ChromeDriver is not a “Chrome server reference”; for remote execution use RemoteWebDriver and a Selenium Grid URL.
What is Maven and why use it?
Maven is a Java build and dependency-management tool driven by pom.xml. It downloads dependencies, manages plugin versions, standardizes build phases, runs tests, packages artifacts, and supports reproducible CI builds. Common commands: mvn clean test, mvn package, mvn verify. It reduces manual JAR management and makes local/CI builds more consistent.
Explain the structure of pom.xml
Core sections include modelVersion, groupId, artifactId, version, packaging, properties, dependencies, dependencyManagement, build/plugins, repositories, and profiles. Example: <groupId>com.example</groupId><artifactId>ui-tests</artifactId> <version>${project.version}</version>. Properties centralize versions; dependencies add libraries; plugins configure tasks such as compiler and Surefire. Parent POMs can provide shared configuration.
How do you parameterize a version in pom.xml?
Define a property and reference it wherever appropriate. Example: <properties><selenium.version>4.x.y</selenium.version> </properties>, then in the dependency use <version>${selenium.version}</version>. For the project version, use a Maven property or parent/version management as supported by the project; modern Maven supports CI-friendly version properties such as ${revision} with appropriate configuration. Prefer one controlled source for versions.
What is Maven Surefire and why is it needed?
Maven Surefire Plugin runs unit and test-framework tests during Maven's test phase. It supports JUnit and TestNG providers and can select tests, pass system properties, configure groups, and run TestNG XML suites. Reports typically appear under target/surefire-reports. Failsafe is commonly used for integration tests during integration-test/verify phases.
What is POM model?
POM can mean two different things: Maven Project Object Model (pom.xml), which describes build coordinates, dependencies, plugins, and configuration; or Selenium Page Object Model, a design pattern where page classes encapsulate locators and page actions. Clarify which meaning the interviewer intends.
What is a constructor and why is it needed?
A constructor initializes a new object. It has the same name as its class and no return type. Constructors can initialize fields, validate inputs, and establish dependencies. Java provides a default no-argument constructor only if no constructor is declared; once you define a constructor, the compiler does not automatically add that default constructor.
List a few WebDriver constructors
WebDriver is an interface and has no constructor. Browser-specific implementations have constructors, for example new ChromeDriver(), new FirefoxDriver(), and new EdgeDriver(); these return driver objects implementing WebDriver. RemoteWebDriver is commonly constructed with a URL and browser Options, for example new RemoteWebDriver(gridUrl, new ChromeOptions()). Constructor availability depends on Selenium version.
What are constructors with parameters?
A parameterized constructor accepts values to initialize object state. Example: class User { private String name; User(String name){ this.name=name; } } then User u=new User("Ravi");. The this keyword distinguishes the instance field from the parameter. You can overload constructors with different parameter lists.
Explain Jenkins
Jenkins is an automation server used for continuous integration and delivery. A pipeline can check out source code, set up the JDK, run Maven tests, publish reports, archive logs/screenshots, and notify a team. Triggers can include commits, pull requests, and scheduled runs. Store credentials in Jenkins credentials or a secret manager, not in source code.
Explain overloading and overriding
Overloading uses the same method name with different parameter lists and is resolved at compile time. Overriding provides a subclass implementation of an inherited instance method with a compatible signature and is resolved at runtime based on the object. Return type alone cannot distinguish overloaded methods. Static methods are hidden, not overridden.
Three environments have text boxes with different labels but similar properties. How do you
enter data and handle exceptions? Do not rely only on shared attributes if they identify multiple fields. Use an environment-specific locator map, a stable container/label relationship, or a data-testid. Wait for the chosen element, enter the value, and catch only expected exceptions with meaningful recovery/logging.
TestNG XML is on one machine; run tests on three other IP-addressed machines
Use Selenium Grid or a remote execution setup. Put test code/configuration where the workers can access it, and point RemoteWebDriver to a Grid endpoint; the Grid routes sessions to nodes. If the goal is three independent machines rather than Grid nodes, use CI agents or remote commands to launch the suite on each machine. A local testng.xml does not itself distribute tests to arbitrary IPs.
Name some exceptions faced in Selenium
Examples include NoSuchElementException, TimeoutException, StaleElementReferenceException, ElementClickInterceptedException, ElementNotInteractableException, NoSuchFrameException, NoSuchWindowException, and InvalidSelectorException. Explain a real occurrence and root cause. Use explicit waits, robust selectors, correct frame/window context, and refreshed locators; do not blindly catch and ignore errors.
What is StaleElementReferenceException?
It occurs when a previously located WebElement no longer refers to the current DOM element, often because the page refreshed, an Angular/React component rerendered, or the element was replaced. Fix it by waiting for the new state and locating the element again. Avoid caching dynamic elements for long periods; use a locator and re-find when needed.
Explain static and final
static members belong to the class, not each object; they can be accessed using the class name. final on a variable prevents reassignment, on a method prevents overriding, and on a class prevents subclassing. A final reference cannot point to another object, but the referenced object's mutable state may still change.
What happens if you change a final value? What exception occurs?
For a local final variable assigned once, a second assignment is a compile-time error, not a runtime exception. Example: final int n=10; n=20; // compile error: cannot assign a value to final variable n. A final object reference cannot be reassigned, though methods may mutate the object if it is mutable. A blank final must be assigned exactly once on every valid construction path.
Additional Java and Selenium questions during the interview
This is a note rather than a specific question. Be ready for follow-ups on Java OOP/collections/exceptions, Selenium locators/waits/frames/windows, test design, TestNG, Maven, debugging, and project examples. Answer the exact question first, then add a concise example.
Windows and pop-ups
For browser tabs/windows, save the original handle, perform the action, wait until the handle count changes, switch to the new handle, interact, and switch back if needed. For JavaScript alerts use driver.switchTo().alert() and accept(), dismiss(), or getText(). HTML modal dialogs are normal DOM elements, not browser alerts, and should be located as elements. Java & Selenium Automation Interview Questions – Part 3 · Saravana Tech.
How do you upload a file?
For a standard HTML input type=file, use sendKeys with the absolute path on the input element; this is usually more reliable than the OS file chooser. Example:.
Explain Page Object Model
POM is a UI automation design pattern where page/component classes contain locators and actions, while test classes contain scenario flow and assertions. It improves reuse, readability, and maintenance. It is not the same as Maven's POM file.
If locators keep changing, how do you manage them?
First determine why they change. Ask developers for stable IDs or data-testid attributes; prefer accessible labels and stable semantic attributes; scope locators to a unique component; centralize them in page objects; and avoid absolute XPath/index-based locators. For unavoidable dynamic values, build a parameterized locator from validated input. Track repeated instability as an application testability issue.
Array-related questions
Know declaration, initialization, indexing, traversal, insertion limitations, sorting, searching, multidimensional arrays, and differences from ArrayList. Java arrays have fixed length; ArrayList resizes dynamically. Example: int[] values={10,20,30}; for(int value:values).
Describe a challenge you faced
Use STAR: Situation, Task, Action, Result. Select a real example such as flaky UI timing, test data collisions, unstable locators, slow suite execution, or environment failures. Explain the root-cause investigation, the change you made, and the verified result. Avoid invented metrics.
A challenge in the interviewer’s current project and whether you have a solution
Ask clarifying questions about constraints, scale, current behavior, and success criteria before proposing a solution. Offer a hypothesis and a small validation plan rather than claiming certainty. Separate what you have done before from what you would investigate. Consider maintainability, observability, test data, and failure recovery.
What is an object? What are its properties?
An object is a runtime instance of a class. It has identity, state (field values), and behavior (methods). A class defines the possible fields and methods; each object holds its own instance state, while static state is shared at class level.
Explain Git
Git is a distributed version-control system. Common commands: git clone, status, add, commit, pull, fetch, branch, switch, merge, rebase, push, and log. Teams use branches, pull requests/code reviews, conflict resolution, and tags. Keep commits focused and never commit secrets or generated files unintentionally.
Explain Agile model
Agile is an iterative approach that delivers work in small increments, incorporates feedback, and adapts to change. Scrum is one Agile framework with defined accountabilities, events, and artifacts. Teams maintain a prioritized backlog, plan a sprint, hold daily Scrum, review the increment, and retrospect to improve. Java & Selenium Automation Interview Questions – Part 3 · Saravana Tech.
Use of getters and setters in Java
Getters expose a field value and setters update it, often with validation. They support encapsulation by keeping fields private and controlling access. Example: private int age; public int getAge(){return age;} public void setAge(int age){if(age<0) throw new IllegalArgumentException(); this.age=age;}. Not every field needs a setter; immutable objects may expose only getters.
What is Hashtable?
Hashtable is a legacy synchronized Map implementation. It does not allow null keys or null values. It is generally superseded by HashMap for single-threaded use or ConcurrentHashMap for concurrent access. Hashtable synchronizes individual operations but is not always the best choice for compound thread-safe logic.
What is HashSet?
HashSet implements Set and stores unique elements using hashing (backed by a HashMap). It does not guarantee iteration order and generally offers average O(1) add, remove, and contains operations when hashes are well distributed. Objects must implement equals() and hashCode() consistently.
How do you connect to a database? Write code
Use JDBC with a JDBC driver, connection URL, credentials supplied securely, and try-with-resources. Example: String url="jdbc:postgresql://host:5432/db"; try(Connection c=DriverManager.getConnection(url,user,password); PreparedStatement ps=c.prepareStatement("SELECT name FROM users WHERE id = ?")){ ps.setInt(1, id); try(ResultSet rs=ps.executeQuery()){.
Get a unique ID from the string "id:9864" in multiple ways
If the format is fixed, substring after the colon is simple: String id=s.substring(s.indexOf(':')+1).trim();. Alternatives include split(":",2).
What is an interface?
An interface defines a contract. A class implements it and supplies required behavior; a class can implement multiple interfaces. Interfaces support loose coupling and polymorphism. They can have abstract, default, and static methods, and modern Java permits private helper methods.
What is inheritance?
Inheritance allows a subclass to inherit accessible behavior and state from a superclass and specialize or extend it. Java classes support single class inheritance and multiple interface implementation. Use inheritance for a genuine “is-a” relationship; prefer composition when it better models reuse.
What is an abstract class?
An abstract class cannot be instantiated directly and may contain abstract methods without bodies and concrete methods with implementations. Subclasses must implement inherited abstract methods unless they are abstract too. It can hold fields and constructors.
How do you insert data into an array?
Arrays have fixed length, so they do not support insertion in place when full. To insert at index i, allocate a larger array, copy elements before i, place the new value, then copy the remainder. EXAMPLE / INTERVIEW TIP Example: int System.arraycopy(a,pos,b,pos+1,a.length-pos);. For frequent insertion, consider ArrayList.
Move to a tag with no attributes—write two ways
Without attributes, locate it by tag name, text, or relationship to a stable nearby element. Examples:.
What framework did you use in your project?
Describe only your real framework. A common answer for web UI automation is a hybrid framework combining POM, data-driven tests, reusable utilities, TestNG, Maven, logging/reporting, and Jenkins. Explain each layer and one reason for choosing it. If your actual project differs, describe that accurately.
Explain TestNG annotations in detail
Common annotations: @BeforeSuite/@AfterSuite once per suite; @BeforeTest/@AfterTest around a testng.xml <test>; @BeforeClass/@AfterClass around class execution; @BeforeMethod/@AfterMethod around each test method invocation; @Test marks a test; @BeforeGroups/@AfterGroups run around group methods; @DataProvider supplies data; @Parameters reads XML parameters; @Factory creates test instances; @Listeners registers listeners. Order can be affected by inheritance, groups, dependencies, parallel execution, and configuration failures.
Explain Jenkins usage
Jenkins automates the test lifecycle: checkout code, build with Maven, run TestNG suites, publish test results, archive artifacts, and notify the team. A pipeline as code (Jenkinsfile) makes the process versioned and repeatable. Secure credentials and make failures diagnosable with logs/screenshots.
Select the second dropdown value without Select class or select command
For a native HTML <select>, keyboard actions can select an option, or click the dropdown and click the desired option if the UI exposes options. Example: WebElement dropdown=driver.findElement(By.id("country")); dropdown.click(); new Actions(driver).sendKeys(Keys.ARROW_DOWN).sendKeys(Keys.ENTER).perform();. This selects relative to the current selection; first establish the current selected option and confirm the expected result. For custom dropdowns, locate and click the second visible option in its overlay instead.
Default dropdown selection is the last value; use Actions to choose the second value
Do not assume one ArrowDown selects the second option when the current selection is the last. Click/open the control, use HOME to move to the first option and then ARROWDOWN once to the second, followed by ENTER, if that control supports keyboard navigation. Example: new Actions(driver).click(dropdown).sendKeys(Keys.HOME).sendKeys(Keys.ARROW_DOWN).sendKeys(Keys.ENTER).perform();. Verify selected text.
Write code for the scenario below
The specific scenario/code referred to is not included in the supplied list, so an exact solution cannot be written without inventing requirements. In an interview, ask for the full scenario, HTML, expected behavior, and constraints. If it refers to the next question, see the frame/window flow in Question 50.
Click OK, handle a frame, select first radio, click Next; repeat for another frame, then next
window Frames are not windows. Keep the current window handle, switch into each frame, select the first radio, click Next, then detect whether the next frame replaces the current one or nests inside it. If a new frame appears at top level, return to defaultContent() and locate that frame; if nested, use parentFrame()/frame switching. After the final Next opens a new window, wait for the handle count to increase and switch to the new handle.
Difference between throw and throws
throw explicitly raises one exception object inside code: throw new IllegalArgumentException("Invalid input");. throws declares in a method signature that the method may propagate one or more exception types: void read() throws IOException. throw is a statement; throws is part of the declaration. Checked exceptions must be caught or declared.
How do you use regular expressions?
Regular expressions match text patterns. In Java use Pattern and Matcher, or String methods such as matches(), replaceAll(), and split(). Example: Pattern p=Pattern.compile("\\d+"); Matcher m=p.matcher("id:9864"); if(m.find()) System.out.println(m.group());. Java string literals require escaping backslashes.
How do you connect to Excel?
In Java automation, Apache POI is commonly used to read/write Excel .xls/.xlsx files. Open with FileInputStream and WorkbookFactory or XSSFWorkbook, access Sheet/Row/Cell, then close resources. For formulas and numeric/date cells, use DataFormatter or evaluate formulas as needed. Store test data outside source code and avoid passwords in plain-text spreadsheets.
What is Selenium Grid? Explain and how used in a project
Grid enables remote WebDriver sessions across multiple browsers, machines, and operating systems, and supports parallel execution. In Selenium Grid 4, components include Router, Distributor, Session Map, Event Bus, and Nodes; standalone mode is simpler for small setups. Use RemoteWebDriver with a Grid URL and browser Options. Explain actual usage honestly—local tests, shared Grid, or CI nodes—and how you isolated test data.
Difference between Selenium and QTP/UFT
Selenium is an open-source browser automation ecosystem focused primarily on web applications and supports several programming languages/browsers. QTP, now UFT One in current product naming, is a commercial testing tool from OpenText with vendor-provided IDE/features and broader packaged integrations depending on license/version. Compare licensing, language/tooling, browser support, integration, and your project needs; neither tool is universally best.
What is implicit wait?
Implicit wait configures WebDriver to poll the DOM for a specified duration when locating elements before returning a not-found error. Example: driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(5));. It applies globally to element-location calls. Prefer explicit waits for specific UI states and avoid mixing wait types because timing can become confusing.
How many waits are there in Selenium?
Interviewers usually expect three common wait approaches: implicit wait, explicit wait, and fluent wait. ExplicitWait and FluentWait are closely related in Selenium's API: WebDriverWait is a specialization of FluentWait for WebDriver. Thread.sleep is a fixed pause, not a Selenium wait strategy, and is generally less reliable. Java & Selenium Automation Interview Questions – Part 3 · Saravana Tech Use page-specific selectors and frame handling.
Difference between implicit and explicit wait
Implicit wait applies to locating elements across the driver and waits up to a configured duration for a match. Explicit wait polls for a specific condition, such as visibility, clickability, text, or URL. Explicit waits are more targeted and easier to diagnose for dynamic UI behavior. Avoid mixing them.
How will you find elements?
Use WebDriver findElement(By...) or findElements(By...). Locators include id, name, className, tagName, linkText, partialLinkText, cssSelector, and xpath. findElement returns the first match or throws NoSuchElementException; findElements returns a list, possibly empty. Prefer stable unique locators.
Write the line of code for findElements
Java example: List<WebElement> elements = driver.findElements(By.cssSelector(".result-item"));. Iterate using for (WebElement element : elements) { System.out.println(element.getText()); }. Import java.util.List and Selenium WebElement/By types.
Element may or may not appear; find it and catch the exception
If presence is optional, findElements avoids an exception: List<WebElement> found=driver.findElements(By.id("optional"));.
What does data-driven testing mean?
Data-driven testing runs the same test logic with multiple data sets, such as valid/invalid credentials, users, or environments. Test logic is separated from inputs. TestNG @DataProvider, CSV, Excel, JSON, and database sources are common approaches. Include clear data ownership, validation, and cleanup.
Are you aware of JDBC?
JDBC (Java Database Connectivity) is Java's standard API for connecting to relational databases, executing SQL, and reading results. It uses a JDBC driver, Connection, Statement/PreparedStatement, and ResultSet. PreparedStatement with parameters helps prevent SQL injection and handles values safely.
How do you connect using JDBC?
Load/add the appropriate database driver dependency, use a JDBC URL, connect with credentials, execute SQL, read the ResultSet, and close resources. Example: try(Connection c=DriverManager.getConnection(url,user,password); PreparedStatement ps=c.prepareStatement("SELECT id,name FROM users WHERE id=?")){ps.setInt(1, id); try(ResultSet rs=ps.executeQuery()) {while(rs.next()) System.out.println(rs.getString("name"));}}. Handle SQLException and use secret management.
If Excel is input, how do you connect to Excel?
Use Apache POI rather than JDBC for a standard local workbook. Read rows/cells from an Excel sheet, convert values safely, and feed them into a TestNG @DataProvider or test. For an Excel file exposed through a database-like service, the approach could differ; clarify what “connect” means.
Explain POM
Selenium Page Object Model encapsulates page locators and actions in page classes, while test classes focus on scenarios and assertions. It improves reuse and maintenance. Example: LoginPage.login(username,password) enters values and clicks sign-in; LoginTest verifies the home page. Maven's pom.xml is a different use of the acronym.
Is POM better or data-driven testing better?
They solve different problems and are not alternatives. POM organizes UI interaction and page logic; data-driven testing supplies multiple inputs to the same test logic. They are commonly combined: a TestNG data provider passes inputs to a test, and the test calls POM page methods. Java & Selenium Automation Interview Questions – Part 3 · Saravana Tech.
What is a hybrid framework?
A hybrid automation framework combines techniques, often POM, data-driven testing, reusable utilities, and sometimes keyword- driven execution. It may include configuration, logging, reporting, test runners, and CI integration. The term is not a strict standard, so explain exactly which patterns your framework combines.
Explain project structure
A common Maven Selenium/TestNG layout: pom.xml; testng.xml; src/main/java/pages, utils, driver, listeners, models; src/test/java/tests; src/test/resources/config, testdata; and target for generated build outputs/reports. Projects may place page objects under test source depending on design. Explain where tests, page objects, data, configuration, and reports live in your actual repository.
What unit-testing frameworks do you know?
Common Java test frameworks include JUnit 4, JUnit 5, and TestNG. TestNG is popular for groups, dependencies, data providers, and suite XML; JUnit is widely used for unit and integration tests and has a strong ecosystem. Choose based on project conventions and features.
Write an assertion comparing actual and expected login name
TestNG: Assert.assertEquals(actualName, expectedName, "Login name mismatch");. JUnit 5: Assertions.assertEquals(expectedName, actualName). Check each framework's argument order: TestNG commonly uses actual then expected; JUnit uses expected then actual. Read the actual displayed value after the page is ready.
Difference between JUnit and TestNG
Both are Java testing frameworks. TestNG includes XML suites, groups, dependencies, @DataProvider, and flexible parallel options. JUnit 5 uses the Platform, Jupiter API, and extensions, with parameterized tests and a broad ecosystem. Capabilities overlap and versions matter; select based on team needs and tooling.
What is SQL?
SQL (Structured Query Language) is used to define, query, and manipulate relational database data. Common statements: SELECT, INSERT, UPDATE, DELETE, CREATE, and ALTER. SQL also supports joins, aggregation, subqueries, transactions, and constraints. Use WHERE clauses carefully for updates/deletes.
What do you know about Oracle?
Oracle Database is a relational database management system. SQL can query and update tables; PL/SQL adds procedural constructs such as variables, loops, procedures, functions, and exception handling. Explain what you actually used—basic SELECT/JOIN/aggregation, data validation, or more advanced work—rather than implying deep Oracle administration experience.
How many joins are you aware of?
Common joins are INNER JOIN, LEFT OUTER JOIN, RIGHT OUTER JOIN, and FULL OUTER JOIN. CROSS JOIN produces a Cartesian product. A self join joins a table to itself; it is a pattern rather than a separate join keyword in many SQL dialects. Oracle also supports join syntax according to its version.
Write SELECT and INSERT queries
SELECT example: SELECT employee_id, employee_name FROM employees WHERE department_id = 10;. INSERT example: INSERT INTO employees (employee_id, employee_name, department_id) VALUES (101, 'Ravi', 10);. Use the actual schema and bind parameters in application code; verify constraints and transaction behavior. Java & Selenium Automation Interview Questions – Part 3 · Saravana Tech.
What is a constructor?
A constructor initializes a new object, shares the class name, and has no return type. It can be no-argument or parameterized; constructors can be overloaded. If no constructor is declared, Java supplies a default no-argument constructor. Constructors are not inherited.
What is an interface?
An interface defines a contract of behavior. Classes implement it, and a class can implement multiple interfaces. Interfaces support polymorphism and reduce coupling between callers and implementations.
What is an abstract class?
An abstract class cannot be instantiated directly and may contain abstract and concrete methods, fields, and constructors. Subclasses must implement abstract methods unless they remain abstract.
Difference between abstract class and interface
An abstract class supports instance state, constructors, and shared implementation; a class can extend only one class. An interface expresses a contract and allows a class to implement multiple interfaces. Modern interfaces can include default/static methods, so the difference is not simply “interface has only abstract methods.”.
Explain method overloading and overriding
Overloading: same name, different parameter lists; compile-time selection. Overriding: subclass supplies a compatible implementation of an inherited instance method; runtime dispatch. Return type alone cannot overload; use @Override to catch signature mistakes.
What is STLC?
STLC means Software Testing Life Cycle: the activities performed to plan, design, execute, and close testing. Typical phases are requirement analysis, test planning, test case development, test environment setup, test execution, defect reporting/retesting/regression, and test closure. Exact phase names vary by organization.
Write the STLC life cycle
A practical sequence: 1) Requirement analysis and testability review. 2) Test planning and estimation. 3) Test case/test data design.
Environment setup. 5) Test execution and defect logging. 6) Retesting fixes and regression testing. 7) Test closure with metrics,
lessons learned, and sign-off. Activities can overlap in Agile teams.
Scenario
The scenario text is missing from the question list. An exact answer would require the complete scenario, expected behavior, and any supplied code/HTML. In an interview, ask a clarifying question instead of inventing requirements.
Do you have Agile knowledge?
Explain Agile principles and your real team practices: iterative delivery, prioritizing a backlog, collaboration, continuous feedback, and adapting to change. If using Scrum, describe Sprint Planning, Daily Scrum, Sprint Review, and Sprint Retrospective; the Product Backlog and Sprint Backlog are key artifacts.
What is a release backlog?
“Release backlog” is not a universally defined Scrum artifact. Teams may use it to mean the prioritized set of features, fixes, and technical work intended for a release. In Scrum, the official artifacts are Product Backlog, Sprint Backlog, and Increment. Explain your organization's usage and how release scope is prioritized and tracked.
What should be discussed in a daily meeting?
In a Daily Scrum, Developers inspect progress toward the Sprint Goal and adapt the plan for the next day. Teams often discuss what was completed, what is next, and blockers, but the meeting is not meant to be a status report to a manager. Keep it focused and take detailed problem-solving offline.
Tell me about yourself
Use a concise introduction: years of experience, current role, manual/automation skills, project responsibilities, leadership, and the role you want. Make every statement consistent with your resume and the job description.
Why Cognizant?
Connect your answer to the specific role, project/domain, technology, learning opportunities, scale, or career path. Avoid generic praise alone. Example: “This role aligns with my QA automation and delivery experience, and I’m interested in contributing to quality engineering while growing in relevant.” Confirm the details before the interview.
What framework did you use?
Describe the framework you actually used. If it combines POM, data-driven tests, TestNG, Maven, utilities, reporting, and Jenkins, call it hybrid and explain the responsibilities of each layer. Do not label it hybrid merely because it has multiple folders.
Draw and explain POM structure
Example structure: pom.xml and testng.xml at root; src/main/java/pages for page objects, utils for helpers, driver for browser lifecycle, listeners for reporting hooks; src/test/java/tests for test classes; src/test/resources for configuration and test data; target for build output/reports. Some projects put page objects in src/test/java. Explain the real structure rather than treating one layout as mandatory.
Write a polymorphism program
Compile-time polymorphism example (overloading): class Calculator { int add(int a,int b){return a+b;} double add(double a,double b) {return a+b;} }. Runtime polymorphism example (overriding): class Animal { void sound(){System.out.println("animal");} } class Dog extends Animal { @Override void sound(){System.out.println("dog");} } Animal a=new Dog(); a.sound(); prints dog.
Overloading and overriding
Overloading is the same method name with different parameters and is resolved at compile time. Overriding is a subclass's replacement implementation of an inherited instance method and is resolved at runtime. Static methods are hidden, not overridden.
HashMap and Hashtable
HashMap is unsynchronized, permits one null key and null values, and is generally preferred for ordinary single-threaded map use. Hashtable is synchronized at method level and prohibits null keys/values; it is a legacy class. For concurrent use, ConcurrentHashMap is usually preferred, but compound operations should use atomic methods.
Vector and ArrayList
Both are resizable-array List implementations that preserve order and allow duplicates. Vector's legacy methods are synchronized; ArrayList is not synchronized and is usually preferred for single-threaded use. Their indexed get is O(1) on average; insertion/removal in the middle requires shifting elements. For concurrent access, choose synchronization/concurrent design based on the use case.
Implicit and explicit wait
Implicit wait globally affects element lookup; explicit wait polls for a specific condition such as visibility or clickability. Explicit waits give better control for dynamic pages. Avoid combining them unless you understand the resulting timeout behavior. Java & Selenium Automation Interview Questions – Part 3 · Saravana Tech.
Regression testing and retesting
Retesting verifies that a specific reported defect is fixed. Regression testing checks that changes have not broken existing functionality. A defect fix typically requires retesting the failed scenario and regression testing related/high-risk areas.
Smoke testing and sanity testing
Smoke testing is a broad, shallow check that a build's critical paths work and is suitable for further testing. Sanity testing is a narrower check focused on a specific change or area after a minor change/fix. Definitions can vary by organization, so state how your team uses them.
Explain your project
Cover business purpose, architecture, your role, team and Agile process, testing scope, automation stack, framework layers, CI/reporting, major risks, and one genuine achievement/challenge. Avoid confidential details and distinguish your contribution from the team's work.
Explain Agile
Agile is an iterative, incremental way of delivering software with collaboration, feedback, and adaptation. Scrum is one framework within Agile. Explain backlog prioritization, sprint planning, daily Scrum, review, retrospective, and how QA contributes throughout the sprint—not only at the end. Java & Selenium Automation Interview Questions – Part 3 · Saravana Tech.
Number of user stories per sprint
There is no fixed number of user stories per sprint. The team selects work based on sprint capacity, story size, historical velocity, dependencies, and the Sprint Goal. A team completing 25 story points does not necessarily need to select the same number of stories every sprint because story sizes differ. EXAMPLE / INTERVIEW TIP Interview answer: “We estimate stories using our team’s agreed method, consider leave and capacity, and select a realistic amount during Sprint Planning.
Complexity of a user story
Complexity is commonly estimated using story points, relative sizing, planning poker, or t-shirt sizes. Consider functional work, technical uncertainty, dependencies, data setup, integrations, non-functional requirements, and testing effort. Story points represent relative effort/complexity/uncertainty, not exact hours. EXAMPLE / INTERVIEW TIP Example: a simple label change may be 1 point; a new workflow with API integration and multiple validations may be 5 or 8 points, depending on team calibration.
Sprint duration
A sprint is a fixed-length event in Scrum, typically one month or less. Many teams use two-week sprints, but the duration is chosen to suit delivery cadence and feedback needs. The sprint duration should remain consistent enough to support planning and inspection. EXAMPLE / INTERVIEW TIP Explain your actual team’s duration, for example: “Our team works in two-week sprints, with planning at the start, daily Scrum, review, and retrospective near the end.” Selenium, Java & Agile Interview Guide – Part 4 · Saravana Tech CTS Selenium Interview Questions with Answers Part 4 (2026) | Saravana Tech Use the selectors, URLs, credentials, and expected text configured for the application. 100 Questions.
Agile versus Waterfall
Waterfall follows a more sequential lifecycle, with phases commonly completed in order. Agile delivers in small increments, welcomes feedback, and adapts priorities as the team learns. Waterfall may suit stable, contract-driven requirements; Agile is useful when frequent feedback and evolving requirements matter. Real projects can use hybrid approaches.
Defect tracking
Defect tracking records, assigns, prioritizes, investigates, fixes, retests, and closes defects. A defect usually includes summary, steps to reproduce, expected/actual result, environment/build, severity, priority, evidence, owner, and status. EXAMPLE / INTERVIEW TIP Tools include Jira, Azure DevOps, Bugzilla, and other defect systems. A good defect is reproducible, evidence-based, concise, and linked to a requirement or test where possible.
Team size
State the actual team size and composition. Explain roles such as Product Owner, Scrum Master, developers, QA/automation engineers, business analyst, DevOps, and shared specialists. Scrum does not prescribe a fixed number for every team; the team should be small enough to coordinate effectively. EXAMPLE / INTERVIEW TIP Example: “Our delivery team has developers and the Product Owner from refinement through release.” Do not invent your team's size.
Client interaction
Explain your real interaction model: requirement walkthroughs, sprint demos, defect triage, clarifications, test sign-off, status reporting, and release discussions. Keep communication factual and document decisions in the agreed tools. EXAMPLE / INTERVIEW TIP Example: “I clarify acceptance criteria early, raise risks during sprint execution, demonstrate completed scenarios, and share defect evidence and test status with client stakeholders.” Adjust to your actual responsibilities.
What is Selenium?
Selenium is an open-source suite of tools for automating web browsers. Selenium WebDriver controls browsers through browser- specific drivers or supported driver management. It supports languages such as Java, Python, C#, and JavaScript. Selenium primarily automates web applications, not native desktop applications.
Store employee names and domains from a web table; select dropdown only for Automation
domain Read the table rows, extract employee name and domain into objects or a Map, and interact with the dropdown only for rows whose domain equals Automation. The exact columns and dropdown locator depend on the supplied HTML. Selenium, Java & Agile Interview Guide – Part 4 · Saravana Tech EXAMPLE / INTERVIEW TIP Example Java: List<WebElement> rows=driver.findElements(By.cssSelector("table tbody tr")); for(WebElement row:rows){.
Tell me about your current project
Use a structured 1–2 minute summary: business purpose, users, major workflows, your role, team/process, testing scope, automation stack, integrations, CI/reporting, and one meaningful outcome. Avoid confidential details. EXAMPLE / INTERVIEW TIP Template: “The project supports manual/automation testing, defect triage, and release reporting. Our stack includes.
What challenges have you faced?
Choose one genuine challenge and explain it with Situation, Task, Action, Result. Common examples include flaky dynamic locators, unstable test data, slow regression runs, environment outages, intermittent API failures, or unclear acceptance criteria. EXAMPLE / INTERVIEW TIP Describe the evidence gathered, root cause, solution, and outcome. Use measurable results only if you can substantiate them.
Which framework are you currently working on?
Describe your actual framework and its layers: test/scenario layer, page objects or screen objects, reusable utilities, driver factory, configuration, test data, assertions, logging/reporting, build tool, and CI. If you use Cucumber, explain Feature files → Step Definitions → Page Objects/Utilities → WebDriver, plus hooks and reports. EXAMPLE / INTERVIEW TIP Do not claim a framework or feature you have not used. Be ready to show one test from scenario to execution and report.
How do you perform a right-click?
Use Selenium Actions.contextClick(). Example: WebElement target=driver.findElement(By.id("record")); new Actions(driver).contextClick(target).perform();. If the menu is a browser-native context menu, WebDriver usually cannot interact with its native entries; if it is an HTML custom menu, locate and click the resulting DOM option.
Implicit wait and explicit wait
Implicit wait applies globally to element-location calls. Explicit wait polls for a specific condition such as visibility or clickability. Example implicit: driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(5)); explicit: new WebDriverWait(driver,Duration.ofSeconds(10)).until(ExpectedConditions.elementToBeClickable(By.id("save"))).click();. Avoid mixing implicit and explicit waits because combined timeouts can be confusing.
What is FluentWait?
FluentWait lets you define timeout, polling interval, and ignored exception types. WebDriverWait is a WebDriver-focused subclass of FluentWait. It is useful when a page condition needs customized polling or transient exceptions must be ignored deliberately. EXAMPLE / INTERVIEW TIP Example: Wait<WebDriver> wait=new FluentWait<> (driver).withTimeout(Duration.ofSeconds(20)).pollingEvery(Duration.ofMillis(500)).ignoring(NoSuchElementException.class);.
Read data from Excel
Apache POI is commonly used to read .xls/.xlsx files. Open a stream, create a Workbook, access a Sheet/Row/Cell, and close resources. Use DataFormatter to preserve displayed values and handle blank/numeric/date/formula cells intentionally. EXAMPLE / INTERVIEW TIP Example: try(InputStream in=Files.newInputStream(Path.of("src/test/resources/data.xlsx")); Workbook wb=WorkbookFactory.create(in)){ Sheet s=wb.getSheet("Users"); DataFormatter fmt=new DataFormatter(); String username=fmt.formatCellValue(s.getRow(1).getCell(0)); }.
What is a Firefox profile?
A Firefox profile stores browser settings such as preferences, extensions, cookies, and other user data. Selenium can configure Firefox through FirefoxOptions and, when needed, a FirefoxProfile. Profiles can make tests resemble a configured user environment, but shared profiles may cause test interference. EXAMPLE / INTERVIEW TIP Modern Selenium example: FirefoxOptions options=new FirefoxOptions(); options.addPreference("intl.accept_languages","en- US"); WebDriver driver=new FirefoxDriver(options);.
How do you handle a proxy?
Configure browser options or system/network settings with the approved proxy host and port, and ensure the machine can reach it. Selenium provides a Proxy capability that can be supplied to browser Options. Authentication and corporate TLS inspection may need environment-specific setup; never bypass security controls without approval. EXAMPLE / INTERVIEW TIP Example: Proxy proxy=new Proxy(); proxy.setHttpProxy("proxy.company.local:8080").setSslProxy("proxy.company.local:8080"); ChromeOptions options=new ChromeOptions(); options.setProxy(proxy); WebDriver driver=new ChromeDriver(options);.
Have you created a framework from scratch?
Answer honestly. If yes, describe requirements, architecture, driver lifecycle, POM, utilities, configuration, data, logging, reporting, build integration, CI, and standards. If you enhanced an existing framework, explain precisely what you designed or implemented. EXAMPLE / INTERVIEW TIP A credible walkthrough includes why you selected each design, how tests are executed, how failures are diagnosed, and how parallel runs are isolated.
What frameworks have you used other than TestNG and POM?
POM is a design pattern, while TestNG is a test runner. Other approaches/tools can include Cucumber BDD, data-driven, keyword-driven, hybrid frameworks, JUnit, Screenplay, or modular frameworks. Name only what you have actually used and explain how it differs. EXAMPLE / INTERVIEW TIP If using Cucumber, explain Gherkin feature files, step definitions, hooks, tags, and runner configuration; POM can still be used underneath.
Explain inheritance, extends, and using another class through an object
Inheritance lets a subclass reuse and specialize accessible members of a superclass; extends declares class inheritance. A class can also use another class by composition—creating/receiving an object and calling its public methods—without inheriting from it. Selenium, Java & Agile Interview Guide – Part 4 · Saravana Tech EXAMPLE / INTERVIEW TIP Example: class BasePage { void waitForPage(){} } class LoginPage extends BasePage { void login(){waitForPage();} }. Composition: LoginPage holds Helper helper; then helper.click(...).
How do you find broken links?
Collect anchor href values, validate non-empty HTTP/HTTPS URLs, and send HTTP requests to check status. Some sites block automated HEAD requests, so retry with GET when appropriate. Avoid treating mailto:, javascript:, fragments, or authenticated links as ordinary web URLs. EXAMPLE / INTERVIEW TIP Example outline: for each a GET; report status >=400 or connection failures.
How do you count all links on a page?
Use findElements(By.tagName("a")) and read the list size. Example: List<WebElement> links=driver.findElements(By.tagName("a")); System.out.println("Link count: "+links.size());. If you mean links with href only, use By.cssSelector("a.
An element was removed in the previous release; how do you verify it is absent?
Use findElements and assert the result is empty, or wait for invisibility if the element might still be transitioning out of the DOM. Example: Assert.assertTrue(driver.findElements(By.id("oldElement")).isEmpty(), "Removed element is still present");. Presence and visibility are different: an element can exist in the DOM but be hidden.
Write XPath using following
The following axis selects nodes that occur after the context node in document order, excluding descendants. Example:.
F2F questions
This is a section label. Prepare to explain your role, project, automation design, Agile workflow, defects, Java, Selenium, TestNG, SQL, Git, and debugging with practical examples.
Where are you currently working?
State your current employer and role truthfully, then briefly describe responsibilities relevant to the vacancy. Do not disclose confidential client information unless authorized.
Tell me about yourself
Give a 60–90 second summary: experience, current role, manual/automation skills, key tools, leadership responsibilities, and why this role fits. Keep details aligned with your resume.
How did you move from manual to automation?
Explain the progression: strong manual testing fundamentals, identifying repetitive/high-value cases, learning Java and Selenium, building small scripts, learning framework patterns, reviewing code, and integrating automation into regression/CI. Share a real example of a manual scenario you automated and how you maintained it. Selenium, Java & Agile Interview Guide – Part 4 · Saravana Tech.
Which methodology does your project follow?
State whether it uses Scrum, Kanban, Waterfall, or a hybrid approach. Explain the actual ceremonies/artifacts and how QA fits into the lifecycle. Do not call a project Agile merely because it has daily meetings.
What is Agile methodology?
Agile delivers software incrementally with collaboration, feedback, and adaptation. Scrum is one Agile framework; its events include Sprint Planning, Daily Scrum, Sprint Review, and Sprint Retrospective. The Product Backlog, Sprint Backlog, and Increment are Scrum artifacts.
What are the phases of STLC?
Common phases are requirement analysis, test planning, test case/test data development, test environment setup, test execution, defect reporting/retesting/regression, and test closure. In Agile, these activities often overlap rather than occur as a strictly linear sequence.
Which STLC phases do you actually work on?
Answer based on your responsibilities. A QA automation lead may participate in requirement analysis, estimation/test planning, test design, data/environment preparation, automation development, execution, defect triage, regression, reporting, and closure. Give one example for each phase you own.
Do you contribute to test planning?
If true, explain scope analysis, risk-based coverage, estimates, resource/capacity planning, environment/data needs, automation feasibility, entry/exit criteria, dependencies, and reporting. If your role is limited, be clear about what you contribute and who approves the plan.
Tell me about your organisation
Give a brief factual overview: company industry, service/product focus, your business unit, and your role. Avoid unsupported claims, confidential revenue/client information, or an overly long corporate history.
Explain your designation
State your official designation and explain actual responsibilities, not just the title. Examples may include test strategy, team coordination, automation reviews, defect triage, stakeholder communication, delivery tracking, and release sign-off support.
Which defect-management tool do you use?
Name the tool actually used, such as Jira, Azure DevOps, or another tracker. Explain how defects are logged, linked to requirements/test cases, assigned, prioritized, tracked, retested, and closed.
What are defect statuses?
Statuses vary by organization. A common workflow is New/Open → Assigned → In Progress → Fixed/Resolved → Ready for Retest → Closed. Other statuses can include Reopened, Rejected/Invalid, Duplicate, Deferred, or Cannot Reproduce. Follow your team's configured workflow.
What status do you set when assigning a defect to a developer?
Use the status configured in your workflow, commonly Assigned or Open with an assignee set to the developer. Some teams assign ownership without changing status. Explain the actual workflow rather than assuming all tools use the same status names. Selenium, Java & Agile Interview Guide – Part 4 · Saravana Tech.
If a defect is not fixed, who can move it to the next iteration?
The Product Owner typically prioritizes backlog items and helps decide what is included in a future sprint/release, in collaboration with the team and stakeholders. QA reports risk and impact; the team does not silently ignore a defect. Severity, release risk, and governance determine escalation.
If a defect is deferred, which status is used?
Common labels include Deferred, Postponed, or Open with a target release/sprint, depending on the defect workflow. Record the reason, risk, owner, and agreed target. Do not mark a defect Closed if it is not fixed unless the process explicitly defines a different disposition.
How do you get requirements?
Sources may include Product Owner/business analyst walkthroughs, user stories, acceptance criteria, business requirement documents, designs, API contracts, refinement sessions, and client discussions. Record questions and confirm decisions in the agreed tool.
How do you analyze requirements?
Check business rules, user roles, inputs/outputs, positive/negative paths, boundary conditions, validations, integrations, security, performance, accessibility, test data, dependencies, and acceptance criteria. Identify ambiguities early and derive traceable test scenarios.
Rate yourself in Java
Give an honest rating and support it with examples of what you can do independently: OOP, collections, exceptions, strings, loops, test utilities, and debugging. Mention an area you are improving. Do not inflate your rating.
What are Java features?
Common features include object-oriented design, platform independence through bytecode/JVM, portability, robustness, security features, multithreading, garbage collection, rich standard libraries, exception handling, and dynamic class loading. Avoid claiming Java is completely platform-independent in every operational detail; the JVM/runtime still matters.
Which Java features do you use in Selenium?
Examples: classes/objects for page objects, interfaces for WebDriver, inheritance for shared page/base classes, encapsulation for private locators, polymorphism through WebDriver implementations, collections for elements/data, exceptions for failure handling, strings/regex for parsing, and lambdas for wait conditions or streams.
Explain inheritance
Inheritance lets a child class reuse and specialize accessible fields/methods from a parent class. Java uses extends for class inheritance and implements for interfaces. Constructors are not inherited, and private members are not directly accessible in subclasses.
Explain encapsulation
Encapsulation bundles data and behavior and restricts direct access to internal state, commonly using private fields and public methods. It enables validation and protects invariants. Example: private balance with deposit() and getBalance() methods instead of allowing arbitrary direct changes.
Explain overloading and overriding
Overloading uses the same method name with different parameter lists and is resolved at compile time. Overriding provides a subclass implementation of an inherited instance method and is resolved at runtime. Return type alone cannot distinguish overloaded methods. Selenium, Java & Agile Interview Guide – Part 4 · Saravana Tech.
Explain polymorphism
Polymorphism means one interface/type can represent different concrete implementations. Compile-time polymorphism is commonly illustrated by method overloading; runtime polymorphism by method overriding and dynamic dispatch. EXAMPLE / INTERVIEW TIP Example: WebDriver driver=new ChromeDriver(); the reference is WebDriver while the runtime implementation is ChromeDriver. Calling driver methods uses the actual implementation.
Explain abstract class
An abstract class cannot be instantiated directly and may include abstract methods, concrete methods, state, and constructors. Subclasses implement abstract methods unless they remain abstract. Use it when related classes share state or implementation.
Explain interface
An interface defines a contract. A class can implement multiple interfaces, supporting loose coupling and multiple inheritance of type. Modern Java interfaces can include abstract, default, and static methods, plus private helper methods.
Rate yourself in Selenium
Rate yourself honestly and explain your practical strengths: locators, waits, frames/windows, dropdowns, actions, file upload, test isolation, debugging, and framework integration. Mention areas still being developed.
What are TestNG annotations?
Common annotations include @BeforeSuite/@AfterSuite, @BeforeTest/@AfterTest, @BeforeClass/@AfterClass, @BeforeMethod/@AfterMethod, @Test, @BeforeGroups/@AfterGroups, @DataProvider, @Parameters, @Factory, and @Listeners. Explain lifecycle annotations in order and note that execution can vary with groups, dependencies, inheritance, and parallelism.
Explain your framework
Describe architecture, test flow, page objects, utilities, driver factory, configuration, test data, assertions, reporting, logging, Maven, TestNG/Cucumber, and Jenkins. Walk through one real scenario from test definition to report and explain how failures are diagnosed.
What is a hybrid framework?
A hybrid framework combines approaches such as POM, data-driven testing, keyword-driven utilities, and reusable components. Explain the exact combination in your project and how it improves reuse, readability, and test-data coverage.
What reports do you use to verify results?
Name your actual reporting tools. TestNG/Surefire can generate XML/text results; ExtentReports or Allure may produce richer HTML reports if configured. Reports should include pass/fail/skip, errors, timing, environment, and useful screenshots/logs for failures.
How do you read Excel?
Use Apache POI with FileInputStream/Files.newInputStream, WorkbookFactory or XSSFWorkbook, and Sheet/Row/Cell. Close resources with try-with-resources. Use DataFormatter when displayed values matter and handle empty cells and formulas.
What repository do you use for files and folders?
Clarify whether the interviewer means source control or artifact storage. Git repositories store versioned source code; artifact/file repositories such as Nexus or Artifactory can store build artifacts and packages. Teams may also use shared drives or cloud storage for approved files. State your actual tool.
If you use Git, how do you add files to the cloud repository?
Typical workflow: git status; git add path/to/file; git commit -m "Add automation update"; git push origin branch-name. First ensure the remote is configured and you are on the intended branch. A pull/rebase may be required before pushing if the remote has new commits.
Why might correct code not be added to Git?
Possible causes: file not staged, ignored by .gitignore, wrong repository/branch, untracked file, merge conflict, failed commit, push rejected, authentication/permission error, or file outside the repository. Diagnose with git status, git check-ignore -v filename, git branch --show-current, git remote -v, and push output.
When do you use Selenium Grid?
Use Grid when you need remote browser execution, parallelism, or coverage across browser/OS combinations. For small local runs it may add unnecessary complexity. Isolate test data and use a compatible browser capability configuration.
Who is the Hub in your project?
In legacy Selenium Grid, the Hub is the central coordinator that receives session requests and routes them to registered Nodes. In Selenium Grid 4 the architecture is more distributed, with Router, Distributor, Session Map, Event Bus, and Nodes; standalone mode packages components together. Describe the version and topology actually used.
What is the use of Grid?
Grid supports remote and parallel test execution across browser/OS configurations, reducing total suite time and expanding compatibility coverage. It also centralizes browser session allocation. Benefits depend on available capacity and test isolation.
When do you run regression testing?
Run regression after code changes that may affect existing functionality, bug fixes, integrations, configuration changes, and before releases. Select scope by risk and impact. In CI, run a fast smoke suite frequently and broader regression at suitable milestones/nightly.
Verification versus validation
Verification asks whether the product is being built according to specifications—reviews, inspections, and static checks. Validation asks whether the product meets user needs—executing tests and evaluating real behavior. A concise phrase is “building the product right” versus “building the right product.”.
How do you verify a page title?
Use driver.getTitle() and compare it with the expected value. Example: String actual=driver.getTitle(); Assert.assertEquals(actual,"Dashboard - Portal","Unexpected page title");. Wait for navigation first if the title changes asynchronously.
Difference between assert and verify
An assertion commonly stops the current test at the first failed check by throwing an assertion error. “Verify” often means a soft assertion that records failures and continues, though exact semantics depend on the framework. In TestNG, Assert is hard assertion; SoftAssert collects failures until assertAll() is called.
Rate yourself in SQL
Give a realistic rating and name the operations you can perform: SELECT, WHERE, JOINs, GROUP BY, aggregates, subqueries, INSERT/UPDATE, and data validation. Be clear about whether you have used Oracle or another database hands-on. Selenium, Java & Agile Interview Guide – Part 4 · Saravana Tech.
How do you connect to a database?
Use JDBC: add the database driver dependency, connect with a JDBC URL and credentials, execute a PreparedStatement, read ResultSet, and close resources. Use try-with-resources, parameterized queries, least-privilege access, and a secure secret store.
Write a query to fetch data
Example: SELECT employee_id, employee_name FROM employees WHERE department_id = 10 ORDER BY employee_name;. Adapt table/column names to the schema. Use a WHERE clause to limit the result and avoid SELECT * when only specific columns are needed.
Verify title, select third dropdown option, submit, accept alert
Illustrative Java Selenium code: String title=driver.getTitle(); Assert.assertEquals(title,"Expected Title"); WebElement dropdown=driver.findElement(By.id("choice")); new Select(dropdown).selectByIndex(2); driver.findElement(By.id("submit")).click(); Alert alert=new WebDriverWait(driver,Duration.ofSeconds(10)).until(ExpectedConditions.alertIsPresent()); alert.accept();. Index 2 is the third option because indexing starts at 0.
How do you locate an element with no attributes?
Use stable text or its relationship to a uniquely identifiable neighboring element/container. Examples: //button[normalize- space()='Continue']; //label neither attributes, text, nor stable structure exists, request a test ID or improve accessibility/markup.
Types of XPath
Interviewers commonly mean absolute XPath and relative XPath. Absolute starts from the root, such as /html/body/div/...; relative searches from matching nodes, commonly //input following-sibling, preceding-sibling, following, preceding, self) and functions such as contains(), starts-with(), and normalize- space().
Which locator is faster?
In general, a stable ID is a good first choice and is typically efficient; CSS selectors are also commonly efficient. XPath can be equally practical in modern browsers, and actual performance differences are usually less important than stability and readability. Choose a unique, robust locator and measure only if performance is a real concern.
Which is faster: absolute or relative XPath?
There is no reliable universal rule that one is always faster. Browser implementation and DOM complexity matter, while locator robustness is usually more important. Relative XPath is typically easier to maintain and less brittle than an absolute path.
Disadvantages of absolute XPath
Absolute XPath is tied to the exact DOM hierarchy, so adding a wrapper or changing layout can break it. It is hard to read and maintain and often depends on positional indexes. Prefer a stable ID, CSS selector, or scoped relative XPath.
What is Maven?
Maven is a build and dependency-management tool for Java projects. It uses pom.xml to define dependencies, plugins, project coordinates, properties, and build configuration. It supports a standard lifecycle and CI integration.
Explain Maven lifecycle
The main default lifecycle phases include validate, compile, test, package, verify, install, and deploy. Running a later phase runs the earlier phases in that lifecycle first. clean is a separate lifecycle that removes build outputs; site generates project documentation. Plugins bind goals to phases. Selenium, Java & Agile Interview Guide – Part 4 · Saravana Tech Use the IDs and expected title defined by the application.
Methods available for JavaScript alerts
Selenium's Alert interface provides accept(), dismiss(), getText(), and sendKeys() (sendKeys is for prompts that accept input). Example: Alert a=driver.switchTo().alert(); String msg=a.getText(); a.accept();. Wait for alert presence before switching.
How do you handle a Yes/No alert?
If it is a JavaScript alert/confirm, Selenium can usually accept or dismiss it; the buttons are browser-defined. If it is an HTML modal with Yes and No buttons, locate and click the corresponding DOM element. Confirm which kind of popup the question describes.
How do you interact with a web table?
Locate rows, then cells within each row. Use row/cell text to identify the target record rather than relying only on row indexes. Example: for each tr, read td cells; if the employee cell matches a name, click the action button within that row. Handle pagination and dynamic tables explicitly.
A two-month calendar shows July and August; date 4 is enabled. How do you select it?
Scope the date locator to the intended month panel; otherwise two calendars may contain a day numbered 4. Example: locate the calendar header whose text is “August”, find its day-cell button with text 4, verify it is enabled, then click it. Avoid global.
What wait methods are used in Selenium?
Common approaches are implicit wait, explicit wait (WebDriverWait), and FluentWait (custom timeout/polling/ignored exceptions). Thread.sleep is a fixed Java pause, not a condition-based Selenium wait, and should generally be avoided for synchronization.
FluentWait syntax and an example
Example: Wait<WebDriver> wait=new FluentWait<> (driver).withTimeout(Duration.ofSeconds(15)).pollingEvery(Duration.ofMillis(300)).ignoring(NoSuchElementException.class);.
Parallel execution through TestNG
TestNG supports parallel execution via testng.xml attributes such as parallel="methods", "classes", or "tests" and thread-count. A DataProvider can also use parallel=true. Ensure each test/thread has its own WebDriver instance, avoid shared mutable state, isolate data, and make reports thread-safe.
Explain your project framework if it uses Cucumber
Explain Feature files written in Gherkin, step definitions binding steps to Java code, hooks for setup/teardown, page objects/utilities for UI actions, runner configuration, tags, test data, reporting, Maven, and CI. Walk through a feature scenario to show how a step invokes a page object and how results are reported.
Write XPath code for textbox, combo box, and input inside a web table
Use the table row as context, identify it by a unique cell, and then locate controls inside that row. Example: WebElement row=driver.findElement(By.xpath("//tr textBox=row.findElement(By.xpath(".//input textBox.sendKeys("QA"); new Select(combo).selectByVisibleText("Automation");. Adapt selectors to the actual HTML. Selenium, Java & Agile Interview Guide – Part 4 · Saravana Tech.
Roles and responsibilities in automation
Common responsibilities include analyzing requirements, choosing automation candidates, designing/maintaining framework components, writing/reviewing scripts, managing test data, executing tests, triaging failures, reporting metrics, integrating CI, collaborating with developers/BA/product owners, and mentoring/reviewing code. Tailor to your actual role.
What is a data-driven framework?
It separates test logic from test data and executes the same scenario with multiple input sets. Data may come from TestNG DataProvider, Excel, CSV, JSON, or a database. Validate data, avoid hardcoded secrets, and ensure unique data and cleanup.
Explain Page Object Model
POM represents each page/component with a class that encapsulates locators and actions. Test classes focus on business flows and assertions. Benefits include reuse, readable tests, and centralized maintenance. POM can coexist with Cucumber and data- driven testing.
What is NullPointerException?
NullPointerException occurs when code dereferences a null reference, such as calling a method on null. Find where the value should have been initialized, validate method returns, and use clear preconditions. Example: String name=null; name.length(); throws NullPointerException. Avoid masking the problem with broad catch blocks.
Which wait methods does WebDriver support?
WebDriver exposes timeouts for implicit wait, page-load timeout, and script timeout through manage().timeouts(). Explicit/Fluent waits are classes from Selenium support APIs rather than WebDriver timeout settings. Example:.
FluentWait and its syntax
FluentWait configures maximum timeout, polling interval, and exceptions to ignore. Example: new FluentWait<> (driver).withTimeout(Duration.ofSeconds(10)).pollingEvery(Duration.ofMillis(500)).ignoring(NoSuchElementException.class).until(d -> d.findElement(By.id("ready")).isDisplayed());. WebDriverWait is a convenient specialization.
What is a default class / abstract class?
Java does not have a general “default class” keyword. A class with no access modifier has package-private access. If the interviewer means a default method, interfaces can provide default method implementations. An abstract class cannot be instantiated and can mix abstract and concrete methods.
Database connection
Use JDBC and a suitable database driver. Obtain a Connection with DriverManager or a connection pool, use PreparedStatement for parameterized SQL, read results through ResultSet, and close resources. Keep credentials outside code and use least- privilege accounts.
Git commands to push code
Typical sequence: git status; git add . (or a specific path); git commit -m "Describe change"; git push origin feature-branch. Before pushing, confirm branch and remote. If rejected, fetch/pull and reconcile changes safely; do not force-push shared branches unless the team explicitly permits it.
ArrayList versus List with code
List is an interface; ArrayList is one implementation. Declare to the interface for flexibility: List<String> names=new ArrayList<>(); names.add("Asha"); names.add("Ravi"); System.out.println(names.get(0));. ArrayList uses a resizable array and offers O(1) average indexed access; List itself cannot be instantiated. Selenium, Java & Agile Interview Guide – Part 4 · Saravana Tech.
Handling dynamic web elements with XPath examples
Use stable attributes/text, scope locators to a unique parent, and wait for the right state. Examples: //button[normalize- space()='Submit']; //div space()='Email']/following::input changing IDs, use a stable prefix only if the pattern is guaranteed. Pair dynamic locators with explicit waits and re-locate after DOM refreshes. Selenium, Java & Agile Interview Guide – Part 4 · Saravana Tech.
Frames and inline frames (iframes) handling
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5.
SQL and JDBC connection establishment
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5.
How to handle a dynamic web table
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6.
What does @Test do in TestNG?
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6.
Take a screenshot in Selenium
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6.
How to underline an element
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6.
Highlight text and get foreground/background colour
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7.
Handle Windows pop-up using Robot class
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7.
How to achieve cross-browser testing
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7.
Get tomorrow's date in dd-MM-yyyy format
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8.
Click an element using JavaScriptExecutor
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8.
Difference between Ant and Maven
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8.
When to use Excel versus CSV as test input? Why?
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8.
Web services basics
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8.
TestNG invocationCount and threadPoolSize
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9.
Enumeration, Iterator, and ListIterator
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9.
Generate random strings and numbers
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9.
Get the number of checkboxes
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9.
Types of CSS selectors
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9.
String, StringBuilder, and StringBuffer
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9.
Multiple inheritance using interfaces
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10.
1000 test cases with defect leakage: strategy
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10.
Scenarios for testing Microsoft Excel using Selenium
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10.
Compare web page data with Excel data
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10.
How do you estimate effort?
. . . . . . . . . . . . . . . . . . . . . . . . . 10.
Which version-control tool do you use and what is the process?
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11.
Did the client agree to ExtentReports?
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11.
Scrum meetings and what do you discuss?
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11.
Innovations in Selenium
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11.
Excel is slow—why use it for test data?
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11.
Have you worked on test plan and test strategy?
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12.
How do you generate failed test cases?
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12.
Capture screenshots only for failed test cases
. . . . . . . . . . . . . . . . . . . . . . . 12.
Button enabled initially and disabled after some time—how verify?
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12.
Retrieve values from a HashMap
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13.
Right-click the mouse
Java, Selenium & Cucumber Interview Guide | Page 3 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13.
How do you verify a highlighted element?
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13.
JavaScriptExecutor drawbacks and alternatives
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13.
How do you check a hidden element?
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13.
Do you know database connections?
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14.
Execute against four environments using Maven
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14.
Assert versus verify
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14.
Explain BDD framework
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14.
How to establish database connection
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14.
Explain XPath and its types
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15.
Scenario-based questions
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15.
Read and write data from Excel
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15.
Why is Cucumber preferred?
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15.
Exceptions faced in Cucumber
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15.
What keywords are used in Cucumber?
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15.
Handle alerts and take a screenshot of an alert
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16.
Reporting tool and code
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16.
Jenkins use and scheduling
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16.
Java code to check a prime number
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16.
GitHub questions and SQL query for highest salary
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17.
TestNG annotations and attributes
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17.
Project domain, application, and framework
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17.
Why create a Maven project?
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17.
How Jenkins is used in your office
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17.
Cucumber framework and mandatory keywords
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17.
Convince a customer to select an automation tool
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18.
Difference between git pull and git fetch
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18.
What is wait and which wait is preferred?
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18.
What is POM and why prefer it?
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18.
isDisplayed versus isEnabled
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18.
Drag and drop code
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18.
Rate yourself in SQL
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18.
SQL sorting
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19.
Cross-browser testing
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19.
DB2 database connectivity code
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19.
Day-to-day responsibilities
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19.
Selenium challenges and selecting automatable cases
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19.
Why move from manual to automation?
Java, Selenium & Cucumber Interview Guide | Page 4 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19.
Relative and absolute XPath for an IRCTC login page
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20.
Jenkins and GitHub
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20.
Roles and responsibilities in your project
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20.
Which test cases will you automate?
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20.
How many test cases can you execute in a day?
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20.
Resolve a Git merge conflict
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20.
Languages usable with Jenkins besides Java
. . . . . . . . . . . . . . . . . . . . . . . . 20.
Why not run code directly in Jenkins without Maven and GitHub?
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21.
Scenario questions and team management
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21.
Explain an automation plan to a client
. . . . . . . . . . . . . . . . . . . . . . . . . . . 21.
You are in Sprint 2 and receive a client issue from Sprint 1
Java, Selenium & Cucumber Interview Guide | Page 5.
Frames and inline frames (iframes) handling
A frame/iframe is a browsing context inside a page. Selenium can switch into it by index, name/id, or a WebElement, then return with defaultContent() or parentFrame(). Prefer stable id/name or locate the iframe element; use explicit waits.
SQL and JDBC connection establishment
JDBC is Java's API for connecting to relational databases. Add the correct JDBC driver dependency, connect using a JDBC URL, use PreparedStatement for parameters, read ResultSet, and close resources with try-with-resources. Keep credentials outside source code.
How to handle a dynamic web table
Locate rows and cells, identify a row by stable business data, and interact within that row rather than relying on row numbers. For pagination, handle each page; for changing DOMs, re-find elements after updates.
Take a screenshot in Selenium
Use TakesScreenshot and save the bytes to a file. Use a unique filename and create the destination folder if needed. File src = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE); Path dest = Paths.get("target", "screenshots", "login-failure.png"); Files.createDirectories(dest.getParent()); Files.copy(src.toPath(), dest, StandardCopyOption.REPLACE_EXISTING); Note: For failure-only screenshots, capture in a TestNG listener's onTestFailure(ITestResult result), using that test's WebDriver instance.
How to underline an element
Selenium does not have a built-in underline method. If the goal is visual highlighting during debugging, use JavaScript to set textDecoration. This changes the page DOM style and is usually for debugging, not functional assertions.
Highlight text and get foreground/background colour
You can temporarily set CSS styles through JavaScript for debugging, and read CSS values with getCssValue. Note that changing the style is not proof the application naturally highlights the element; verify expected style before modifying it.
Handle Windows pop-up using Robot class
Robot can send OS-level keyboard/mouse events, but it is fragile and depends on focus, OS, timing, and desktop availability. Prefer WebDriver sendKeys() for file inputs and Alert APIs for JavaScript alerts. Robot is mainly a fallback for native dialogs that WebDriver cannot control. Example for a native file chooser (Windows): Robot robot = new Robot(); robot.delay(1000); StringSelection path = new StringSelection("C:\\files\\document.pdf"); Toolkit.getDefaultToolkit().getSystemClipboard().setContents(path, null); robot.keyPress(KeyEvent.VK_CONTROL); robot.keyPress(KeyEvent.VK_V); robot.keyRelease(KeyEvent.VK_V); robot.keyRelease(KeyEvent.VK_CONTROL); robot.keyPress(KeyEvent.VK_ENTER).
How to achieve cross-browser testing
Parameterize browser selection and create the appropriate WebDriver/Options for Chrome, Firefox, and Edge. Run the same tests against each browser using TestNG parameters, Maven profiles, or a CI matrix. For remote parallel runs, use Selenium Grid and RemoteWebDriver. Example browser factory:.
Get tomorrow's date in dd-MM-yyyy format
Use LocalDate and DateTimeFormatter; this avoids manual month/year rollover bugs. LocalDate tomorrow = LocalDate.now().plusDays(1);.
Click an element using JavaScriptExecutor
Use JavaScript click only when normal WebDriver click is unsuitable and the reason is understood. A JS click bypasses some user-interaction checks, so it can hide overlay or usability issues.
Difference between Ant and Maven
Ant is a flexible build tool driven by explicitly written XML targets and tasks; it does not impose a standard project lifecycle or built-in dependency management. Maven uses a convention-based lifecycle, POM, dependency management, and plugin ecosystem. Ant offers flexibility; Maven offers standardization and easier dependency handling.
When to use Excel versus CSV as test input? Why?
CSV is lightweight, fast, simple, diff-friendly, and suitable for flat tabular data without formatting or multiple sheets. Excel is useful when business users maintain multiple sheets, formulas, cell formatting, or workbook-based templates. Excel parsing has more overhead, so avoid repeatedly opening the workbook for every test; load once or cache parsed data when safe. Note: Choose based on who maintains the data, structure, size, version-control needs, and required features—not because one format is universally better.
Web services basics
A web service exposes functionality over a network. REST commonly uses HTTP methods (GET, POST, PUT, PATCH, DELETE), resources, status codes, headers, and JSON. SOAP is a protocol using XML envelopes and often WSDL contracts. API testing validates status, schema, payload, authentication, error handling, and business rules.
TestNG invocationCount and threadPoolSize
invocationCount specifies how many times a @Test method should run. threadPoolSize specifies the number of threads used for those invocations when invocationCount creates repeated invocations; threadPoolSize is relevant with invocationCount. TestNG suite-level parallel execution is configured separately in testng.xml.
Enumeration, Iterator, and ListIterator
Enumeration is a legacy read-only traversal interface, mainly used with Vector/Hashtable; it has hasMoreElements()/nextElement(). Iterator traverses collections with hasNext()/next() and may support remove(). ListIterator works only with List and supports forward/backward traversal, indexes, add(), set(), and remove(). Note: Use Iterator for general collection traversal; ListIterator when you need bidirectional List traversal or controlled replacement/insertion.
Generate random strings and numbers
Use SecureRandom for security-sensitive values and ThreadLocalRandom/Random for ordinary test data. UUID is convenient for unique IDs. Avoid relying on random values without logging them or controlling reproducibility.
Get the number of checkboxes
Find checkbox inputs and count them. If only visible checkboxes should count, filter by isDisplayed().
Types of CSS selectors
Common CSS selectors include tag (input), ID (#username), class (.primary), attribute ( compound (input.required), descendant (form input), child (ul > li), multiple selector (h1, h2), prefix/suffix/contains attributes ( :first-child and :nth-of-type(). Selenium supports CSS selectors supported by the browser; not all CSS features are locator features in every context.
String, StringBuilder, and StringBuffer
String is immutable; changes create new String objects. StringBuilder is mutable and generally faster for repeated concatenation in a single thread. StringBuffer is mutable and synchronizes its methods, making it thread-safe at method level but usually slower than StringBuilder. Use String for fixed text, StringBuilder for building text in loops, and StringBuffer only when its synchronization semantics are needed.
Multiple inheritance using interfaces
Java classes cannot extend multiple classes, but can implement multiple interfaces. This provides multiple inheritance of type and allows a class to implement separate contracts.
1000 test cases with defect leakage: strategy
Do not simply rerun all tests without analysis. Triage leaked defects by severity, customer impact, and escape point; perform root-cause analysis; map gaps to requirements, risk areas, and test layers; add missing tests; strengthen code reviews/static/API/integration checks; stabilize environments and test data; prioritize automation for repeatable high-risk regression; and track escape rate and recurrence. Note: A practical plan: 1) classify escaped defects; 2) identify why current tests missed them; 3) add targeted regression cases; 4) prioritize critical business journeys; 5) integrate smoke/regression into CI; 6) monitor leakage trend and flaky-test rate. 1000 tests alone do not.
Scenarios for testing Microsoft Excel using Selenium
Selenium automates the web application interface, not the native Excel desktop app itself. If Excel is accessed through a web application such as Excel for the web, test UI workflows like opening a workbook, editing cells, saving, sharing, filtering, and validating messages. For workbook file content, use Apache POI or another file-processing library instead of Selenium. Note: Possible web UI cases: open workbook, edit a cell, apply filter, save changes, verify permission behavior, validate error banners, and confirm concurrent-edit messages.
Compare web page data with Excel data
Read expected values from Excel with Apache POI, read actual values from the page, normalize whitespace/case/date formats where appropriate, and compare row by row. Report all mismatches with row/column details rather than stopping at the first one. Example outline:.
How do you estimate effort?
Break work into activities: requirement analysis, test design, test data/environment, automation development, reviews, execution, defect triage, maintenance, and reporting. Estimate complexity, dependencies, uncertainty, team capacity, and historical velocity; include contingency for risks. Note: In Agile, estimate stories collaboratively using story points or a team-agreed method. For test effort, use analogous past work or bottom-up task estimates and revise as uncertainty reduces.
Which version-control tool do you use and what is the process?
If using Git, a typical workflow is pull/fetch, create or switch to a feature branch, modify code, run tests, inspect git status/diff, add and commit, push, create a pull request, get review, resolve conflicts, and merge through the team's policy. Java, Selenium & Cucumber Interview Guide | Page 11 git switch -c feature/login-test git status git add src/test/java git commit -m "Add login test" git push -u origin feature/login-test Note: Follow branch protections and never commit credentials.
Did the client agree to ExtentReports?
Answer based on actual project governance. Explain how reporting requirements were discussed—readability, pass/fail/skip, screenshots, logs, trends, access, and CI publishing—and who approved the tool. If the project uses a different tool, say so honestly. Note: Do not claim client approval unless it happened.
Scrum meetings and what do you discuss?
Daily Scrum focuses on progress toward the Sprint Goal and adapting the plan. Sprint Planning selects work and sets a goal; refinement clarifies upcoming stories; Review demonstrates the increment and gathers feedback; Retrospective identifies process improvements. QA may raise blockers, test progress, risks, defects, and readiness, keeping detailed troubleshooting outside the daily meeting.
Innovations in Selenium
Examples of useful improvements include reusable locator utilities, smart explicit-wait wrappers, automatic failure screenshots, parallel-safe driver management, data factories, flaky-test analytics, CI smoke gates, API setup to reduce UI setup time, and accessibility checks. Selenium 4 also supports relative locators, improved Grid architecture, and Chrome DevTools Protocol integrations in supported setups. Note: Describe an innovation you personally implemented, the problem it solved, and the evidence of improvement. Avoid calling ordinary framework setup an innovation without context.
Excel is slow—why use it for test data?
Excel is convenient for business-owned data but may be slower than in-memory fixtures, JSON, or CSV, especially if reopened for each test. Read the workbook once per suite/data provider, cache immutable test data when appropriate, avoid shared mutable workbook objects across parallel threads, and use CSV/JSON/database fixtures for large or machine-maintained datasets. Note: The format should fit the data owner and workflow. Performance issues are usually about repeated I/O and design, not simply the .xlsx extension.
Have you worked on test plan and test strategy?
Explain only the work you performed. A test strategy is the higher-level approach: scope, levels, tools, risks, automation, environments, and quality objectives. A test plan applies that approach to a project/release: scope, schedule, roles, estimates, entry/exit criteria, deliverables, and risks. In some organizations the documents are combined.
How do you generate failed test cases?
In TestNG, failed tests appear in TestNG/Surefire results. You can use an ITestListener to capture failure details, or rerun failures through a generated failed-suite XML when supported by the TestNG execution flow. For Maven, inspect target/surefire-reports and configure CI to publish test results. Example listener: public void onTestFailure(ITestResult result) {.
Capture screenshots only for failed test cases
Implement TestNG ITestListener.onTestFailure and obtain the WebDriver instance associated with the failed test/thread. Save a screenshot with a unique test name and timestamp. A ThreadLocal<WebDriver> driver factory is helpful for parallel execution. public void onTestFailure(ITestResult r) {.
Button enabled initially and disabled after some time—how verify?
Verify the initial state, trigger or wait for the transition condition, then assert the disabled state. Use explicit waits instead of Thread.sleep when possible.
Retrieve values from a HashMap
Use get(key), keySet(), values(), entrySet(), or getOrDefault(). Iterating entrySet is efficient when both keys and values are needed.
Right-click the mouse
Use Actions.contextClick(element).perform().
How do you verify a highlighted element?
Read the relevant CSS properties, such as border-color, background-color, outline-color, or box-shadow, and compare with the expected computed style. A screenshot can help visually, but assertions should target the intended property.
JavaScriptExecutor drawbacks and alternatives
JavaScriptExecutor can bypass normal user interaction checks, hide real UI problems, and make tests less representative of user behavior. Prefer WebDriver click/sendKeys/actions and explicit waits first. JS is useful for reading DOM properties, scrolling, or special cases where normal interaction is impossible and the reason is documented.
How do you check a hidden element?
Use findElements to determine DOM presence, isDisplayed() to check visibility, and getAttribute/style only if needed. A hidden element can exist in the DOM while isDisplayed() returns false. If it is not in the DOM, findElements returns an empty list.
Do you know database connections?
Yes, if true: explain JDBC, driver dependency, connection URL, credentials, PreparedStatement, ResultSet, transactions, and closing resources. Use database queries to validate persisted state where permitted, and avoid using direct DB checks as a substitute for all UI behavior. Java, Selenium & Cucumber Interview Guide | Page 14.
Execute against four environments using Maven
Use Maven profiles or system properties to select environment configuration, and pass the profile/property in each run. Avoid duplicating test code. Keep environment URLs and secrets in configuration/CI variables, not source code. Pass the environment as a system property: mvn test -Denv=qa1 mvn test -Denv=qa2 Note: A profile can set environment-specific properties; alternatively execute four CI matrix jobs.
Assert versus verify
A hard assertion stops the test method at the first failed assertion. A soft assertion records failures and allows later checks to run; in TestNG, call SoftAssert.assertAll() at the end or the failures will not fail the test. SoftAssert soft = new SoftAssert(); soft.assertEquals(actualTitle, expectedTitle); soft.assertTrue(saveButton.isDisplayed()); soft.assertAll(); // required - reports all collected failures.
Explain BDD framework
Behavior-Driven Development expresses behavior in business-readable Given/When/Then scenarios. With Cucumber, Feature files contain Gherkin, step definitions map steps to code, hooks manage setup/teardown, and page objects/utilities implement actions. BDD works best when scenarios are collaborative and express business behavior rather than low-level click sequences. Example scenario: Scenario: Successful login Given I am on the login page When I sign in with valid credentials Then I should see the dashboard.
How to establish database connection
Use JDBC with the correct driver and URL; create a Connection, use PreparedStatement, process ResultSet, and close resources. Use secure credentials and least-privilege access. See Question 2 for a full example.
Explain XPath and its types
Common interview categories are absolute XPath (/html/body/...) and relative XPath (//input XPath expressions can use attributes, text, predicates, functions, and axes. Examples:.
Scenario-based questions
The prompt does not include a specific scenario. For any scenario, clarify expected behavior, initial state, data, locator/DOM constraints, and error handling; then state the approach and code. Do not claim an exact answer where the actual scenario is missing.
Read and write data from Excel
Use Apache POI. Read with WorkbookFactory/XSSFWorkbook and DataFormatter; write by creating/updating cells and calling workbook.write(OutputStream). Always close workbook and streams, and avoid concurrent writes to the same workbook. Example write: try (Workbook wb = new XSSFWorkbook(); OutputStream out = Files.newOutputStream(Path.of("target/result.xlsx"))) { Sheet s = wb.createSheet("Results"); s.createRow(0).createCell(0).setCellValue("Status"); s.getRow(0).createCell(1).setCellValue("PASS"); wb.write(out);.
Why is Cucumber preferred?
Cucumber can make business behavior readable to non-technical stakeholders and supports collaboration through Gherkin scenarios, reusable steps, tags, hooks, and reports. It is not automatically better for every project: it adds step-definition maintenance and can become verbose if scenarios describe UI mechanics instead of behavior.
Exceptions faced in Cucumber
Common issues include UndefinedStepException/undefined steps, ambiguous step definitions, duplicate glue matches, failed hooks, parameter conversion errors, and assertion/runtime exceptions inside step definitions. Exact exception names vary by Cucumber version. Fix by aligning feature wording with step definitions, avoiding overlapping expressions, configuring glue paths, and preserving failure stack traces.
What keywords are used in Cucumber?
Gherkin keywords include Feature, Rule, Scenario, Scenario Outline, Examples, Given, When, Then, And, But, Background, and doc strings/data tables. Some are structural, and step keywords express context/action/outcome. The exact supported syntax depends on Gherkin version.
Handle alerts and take a screenshot of an alert
For JavaScript alerts, switch to Alert, read text, and accept/dismiss. Selenium screenshots generally capture the browser viewport but native alert rendering can be browser-dependent; screenshot before interacting may or may not include the alert. Capture a screenshot of the page and record alert.getText() for reliable evidence. Alert a = new WebDriverWait(driver, Duration.ofSeconds(10)) .until(ExpectedConditions.alertIsPresent());.
Reporting tool and code
Name the tool actually used (for example ExtentReports, Allure, or built-in TestNG/Surefire reports). A TestNG listener can attach screenshots and failure messages; reporting APIs vary by version. Illustrative ExtentReports pattern: ExtentReports extent = new ExtentReports(); ExtentTest test = extent.createTest("Login test"); test.pass("Login successful"); extent.flush(); Note: Configure a report destination and ensure flush/cleanup occurs even when tests fail. Do not claim client approval unless confirmed.
Jenkins use and scheduling
Jenkins automates checkout, build, test execution, report publishing, artifact archiving, and notifications. Schedule a job through Build Triggers/cron or use a Pipeline Jenkinsfile with a cron trigger. Jenkins cron syntax uses five fields; H/ notation spreads load across time. Example Jenkinsfile snippet: pipeline { agent any triggers { cron('H 2 * * 1-5') } stages { stage('Test') { steps { sh 'mvn clean test' }.
Java code to check a prime number
Check numbers below 2 as non-prime; test divisors only up to the square root. static boolean isPrime(int n) {.
GitHub questions and SQL query for highest salary
GitHub hosts Git repositories and adds collaboration features such as pull requests, reviews, issues, and Actions. Git is the version-control tool; GitHub is a hosting/collaboration platform. To fetch the employee(s) with the highest salary, use a subquery to preserve ties. SELECT employee_id, employee_name, salary Java, Selenium & Cucumber Interview Guide | Page 17 FROM employees WHERE salary = (SELECT MAX(salary) FROM employees); Note: To fetch one row only, use ORDER BY salary DESC with database-specific limiting syntax, but that may discard ties.
TestNG annotations and attributes
Core lifecycle annotations: @BeforeSuite/@AfterSuite, @BeforeTest/@AfterTest, @BeforeClass/@AfterClass, @BeforeMethod/@AfterMethod, @BeforeGroups/@AfterGroups. @Test attributes include priority, groups, dependsOnMethods/Groups, invocationCount, threadPoolSize, dataProvider, enabled, timeOut, expectedExceptions, and alwaysRun. @DataProvider supplies data; @Parameters reads XML parameters; @Factory creates test instances; @Listeners registers listeners. Exact behavior depends on TestNG version and configuration.
Project domain, application, and framework
Explain the real business domain, main workflows, users, architecture at a high level, your role, tools, framework layers, CI/reporting, and key quality risks. Do not disclose confidential client or production details. Use a real example to show how a requirement becomes a test and report.
Why create a Maven project?
Maven standardizes build structure and lifecycle, resolves dependencies, manages plugins/versions, and makes local/CI execution repeatable. A pom.xml documents project coordinates, dependencies, properties, and plugins. Maven is not mandatory for Java, but it reduces manual build and JAR management.
How Jenkins is used in your office
Describe actual pipeline steps: source checkout, build, test execution, report publication, screenshots/log archiving, and notifications. Mention schedule or trigger type only if you know it. If you have only run jobs rather than maintained pipelines, state that distinction.
Cucumber framework and mandatory keywords
A feature typically starts with Feature and contains Scenario/Scenario Outline; Given/When/Then steps describe context, action, and outcome. Examples is used with Scenario Outline. Some keywords such as Rule, Background, And, and But are optional depending on scenario structure. Step definitions and glue code are required for executable matching steps.
Convince a customer to select an automation tool
Start with requirements and constraints: application technology, browser/platform coverage, team skills, licensing, integrations, security, maintainability, reporting, CI, and total cost. Run a small proof of concept on representative high-risk workflows and compare stability, execution time, maintainability, and support. Recommend the tool based on evidence and customer priorities, not preference alone. Java, Selenium & Cucumber Interview Guide | Page 18.
Difference between git pull and git fetch
git fetch downloads remote refs/commits without merging them into the current branch. git pull performs fetch followed by integration (merge or rebase, depending on configuration/flags). Fetch lets you inspect changes first; pull updates the current branch. Teams should follow their configured strategy.
What is wait and which wait is preferred?
Waits synchronize tests with asynchronous UI behavior. Explicit waits are generally preferred for dynamic UI because they wait for a specific condition, such as visibility or clickability. Implicit wait applies globally to element lookup; FluentWait customizes polling/ignored exceptions. Avoid fixed sleeps except for rare diagnostic cases.
What is POM and why prefer it?
Page Object Model puts page locators and actions in page/component classes, leaving tests to express business scenarios and assertions. It reduces duplication and centralizes maintenance when UI locators change. It is a design pattern, not a test runner or Maven POM file.
isDisplayed versus isEnabled
isDisplayed() indicates whether the element is rendered/visible according to WebDriver. isEnabled() indicates whether the control is enabled for interaction, typically relevant to form controls. An element can be visible but disabled; visibility and enabled state are different.
Drag and drop code
Use Actions.dragAndDrop(source,target).perform().
Rate yourself in SQL
Give an honest rating supported by actual skills: SELECT, WHERE, joins, GROUP BY, aggregate functions, subqueries, insert/update, and test-data validation. Mention what you can do independently and what you are learning.
SQL sorting
Use ORDER BY. ASC is ascending and DESC descending. Without ORDER BY, result order is not guaranteed. SELECT employee_name, salary FROM employees ORDER BY salary DESC, employee_name ASC; Java, Selenium & Cucumber Interview Guide | Page 19.
Cross-browser testing
Run the same functional scenarios across required browser/OS combinations. Parameterize browser creation, use compatible browser options, isolate data, and record browser versions. Grid/CI matrices can parallelize runs; focus coverage based on customer usage and known browser differences.
DB2 database connectivity code
Use the IBM DB2 JDBC driver and a DB2 JDBC URL. Exact URL, driver dependency, authentication, and TLS settings depend on your DB2 deployment.
Day-to-day responsibilities
Describe your actual day: review requirements and stories, attend refinement/planning/daily meetings, design tests, maintain automation, execute suites, analyze failures, raise/triage defects, review code, update reports, and coordinate release readiness. Tailor it to your role and avoid claiming tasks you do not perform.
Selenium challenges and selecting automatable cases
Common challenges include dynamic DOMs, timing/flaky tests, unstable test data, browser differences, CAPTCHA/OTP constraints, environment instability, and slow suites. Automate stable, repeatable, high-value regression and data-heavy scenarios; avoid automating one-off, rapidly changing, subjective visual, or blocked third-party flows without a clear ROI. Keep exploratory testing manual and complement automation.
Why move from manual to automation?
Explain that manual testing built your understanding of business workflows and risk, then you identified repeatable regression scenarios where automation improved consistency and feedback speed. Mention your learning path and a real example. Avoid implying manual testing is unnecessary; both approaches serve different purposes.
Relative and absolute XPath for an IRCTC login page
Use the actual DOM, not a guessed site structure. Absolute XPath starts at the document root, e.g. /html/body/... and is fragile. Relative XPath starts with // and uses stable attributes/text, e.g.
Jenkins and GitHub
GitHub stores version-controlled code and supports pull requests/reviews. Jenkins checks out a branch, builds/tests it, publishes results, and can notify the team. A webhook or polling schedule can trigger Jenkins after pushes. Use credentials securely and branch protections to control merges.
Roles and responsibilities in your project
State your real scope: requirement analysis, test planning, automation design/coding, code reviews, framework maintenance, execution, defect triage, CI/reporting, stakeholder updates, and mentoring/coordination. Distinguish work you personally own from team responsibilities.
Which test cases will you automate?
Prioritize high-value, repeatable, stable tests: smoke/sanity, critical business paths, regression, data-driven validations, API/UI integration checks, and cross-browser flows with frequent repetition. Avoid automating unstable requirements, one-time scenarios, subjective usability judgments, or expensive setup with little return unless risk justifies it.
How many test cases can you execute in a day?
There is no universal number. It depends on test complexity, environment, data setup, execution time, failure analysis, and whether tests are manual or automated. Give a truthful range from your own metrics and distinguish tests executed from tests analyzed and defects triaged.
Resolve a Git merge conflict
Run git status to identify conflicted files; open each file and resolve conflict markers; inspect the result, run tests, git add resolved files, then git commit (for merge) or continue the rebase. Do not blindly choose one side without understanding changes. git fetch origin git merge origin/main # edit the conflicted files, then: git add <file> git commit Note: For a rebase, use git rebase --continue after staging. Coordinate with teammates and avoid force-pushing shared history.
Languages usable with Jenkins besides Java
Jenkins can orchestrate builds/tests for many languages, including Java, JavaScript/TypeScript, Python, C#, Go, Ruby, PHP, and shell/PowerShell scripts, depending on installed tools and plugins. Jenkins itself is commonly extended through plugins and pipelines; it is not limited to Java.
Why not run code directly in Jenkins without Maven and GitHub?
Jenkins can run scripts directly, and GitHub is not mandatory. Git provides source versioning and collaboration; Maven provides repeatable dependency/build/test lifecycle for Java. Without them, you must manage source retrieval, JARs, classpaths, build steps, and versions manually. For small scripts direct execution can work, but version control/build tools improve reliability and traceability.
Scenario questions and team management
Clarify the scenario, identify impact and urgency, gather facts, communicate ownership, agree a plan, track actions, and escalate risks early. For team management, prioritize work transparently, support blockers, review quality, give feedback, and protect focus. Use a real example and measurable result where possible.
Explain an automation plan to a client
Start with objectives and success criteria; understand the application, risks, environments, data, browsers, and release cadence; evaluate tools; run a proof of concept; propose framework architecture; prioritize candidates by ROI/risk; define reporting/CI/security; estimate effort and dependencies; pilot, review, and scale. Explain what remains manual and the maintenance cost. Obtain agreement on scope and metrics.
You are in Sprint 2 and receive a client issue from Sprint 1
Triage severity, customer impact, reproducibility, and release risk immediately. Create/link a defect or support item, inform the Product Owner/team, and agree whether it is an urgent production fix or can be prioritized in the backlog. For a critical issue, the team may need to replan sprint work with stakeholder agreement; do not silently add work or abandon the Sprint Goal. Add regression coverage after the fix.