Java constructor
A constructor initializes a new object. It has the same name as the class and no return type. Constructors can be overloaded. If you declare no constructor, Java normally supplies a default no-argument constructor.
Prepare for Photon interviews with 56 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.
These study answers summarize the associated PDF material. Adapt personal, project and experience details to your own background.
A constructor initializes a new object. It has the same name as the class and no return type. Constructors can be overloaded. If you declare no constructor, Java normally supplies a default no-argument constructor.
Method overriding occurs when a subclass provides a new implementation of an inherited instance method with a compatible signature. Runtime polymorphism selects the implementation based on the actual object type. Static methods are hidden, not overridden.
A constructor initializes object state and required dependencies at creation time. In a Selenium Page Object, a constructor commonly receives the shared WebDriver instance.
• Abstract class: can have constructors, instance fields, abstract methods, and implemented methods; a.
A static method belongs to the class, not to an individual object. Call it using the class name. A static method cannot directly access instance fields or use this.
Selenium itself automates browser interactions; the test framework (e.g., TestNG) marks tests passed or failed based on exceptions and assertions. On failure, capture useful diagnostics, record the stack trace, take a screenshot, publish the report, and clean up the browser. Avoid catching and suppressing failures.
Common @Test attributes include priority, groups, dependsOnMethods, dependsOnGroups, invocationCount, threadPoolSize, enabled, timeOut, expectedExceptions, dataProvider, and dataProviderClass. Use only the attributes that support a real test requirement.
File src = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE); Files.copy(src.toPath(), Paths.get("target/screenshots/page.png"), StandardCopyOption.REPLACE_EXISTING); Imports include java.io.File, java.nio.file.Files, Paths, StandardCopyOption, and Selenium screenshot classes. Use unique filenames per test; screenshots are especially useful on failure.
For a native HTML select element, use Selenium's Select class. Select by visible text, value attribute, or zero-based index. For custom dropdowns built with div/button elements, click the dropdown and then locate/click the desired option; Select does not work on those.
Locate the table, find the row using a unique business value, then find the target cell/action inside that row. This is safer than using a hard-coded row index.
The exact answer depends on the supplied table and requested operation (for example, find a value, count rows/columns, select a row, or click Edit). Clarify the target column/value, then use row-scoped locators. Example pattern:.
Give a defensible rating and explain what you can do at that level. Example: “I would rate myself 7.5 or 8 out of 10 for Java automation development. I’m comfortable with OOP, strings, collections, exception handling, file handling, and writing reusable framework utilities. I continue to improve in concurrency, JVM internals, and advanced design patterns.” Choose the rating that matches your skills and be ready for follow-up coding.
Inheritance lets a subclass reuse and specialize accessible behavior from a superclass using extends. Java classes support single inheritance; a class can implement multiple interfaces.
The Java Collections Framework provides reusable data structures and algorithms. • List: ordered, allows duplicates; e.g., List<WebElement> for rows/options. • Set: unique elements; e.g., Set<String> for browser window handles. • Map: key-value pairs; e.g., Map<String,String> for configuration/test data. • Queue/Deque: useful for ordered processing. Benefits include reuse, standard APIs, type safety with generics, easier data manipulation, and a choice of implementation based on ordering, uniqueness, and performance needs.
String is a Java class representing a sequence of characters. String objects are immutable: operations such as replace or concat return a new String rather than changing the original.
An abstract class is declared with abstract and cannot be instantiated directly. It can contain abstract methods that subclasses must implement (unless they remain abstract) and concrete methods that subclasses inherit.
Both are capable Java test frameworks. TestNG is often chosen in Selenium projects for built-in groups, flexible suite XML, dependencies, DataProvider, and parallel-execution configuration. JUnit (especially JUnit 5) is also strong and has an extensive extension ecosystem. Explain why TestNG fits your actual project rather than claiming JUnit cannot do something.
An IDE (such as IntelliJ IDEA, Eclipse, or VS Code) is software used to write, navigate, debug, and run code. Selenium WebDriver is an automation API/library that drives browsers. They serve different purposes and are used together.
• @BeforeSuite / @AfterSuite: once around a suite. • @BeforeTest / @AfterTest: around a TestNG XML <test> block. • @BeforeClass / @AfterClass: around test methods in a class. • @BeforeMethod / @AfterMethod: before/after each @Test method. • @BeforeGroups / @AfterGroups: around specified groups. • @Test: defines a test method. • @DataProvider: supplies data sets; @Parameters reads XML parameters; @Listeners registers listeners.
Keywords are reserved words with defined meaning in Java and cannot be used as ordinary identifiers. Examples include class, interface, extends, implements, public, private, protected, static, final, abstract, void, return, if, else, switch, case, for, while, do, break, continue, try, catch, finally, throw, throws, new, this, super, synchronized, volatile, transient, native, package, import, instanceof, enum, assert, and strictfp. true, false, and null are literals, not keywords.
TestNG organizes and executes tests; supplies lifecycle hooks, assertions, groups, dependencies, parameterization, DataProvider, parallel execution, and listener/reporting integration. It is not required by Selenium itself, but it helps manage larger suites.
A data-driven approach runs the same test logic with different data sets. Excel data can be read with Apache POI and supplied to TestNG through @DataProvider. Keep the test logic separate from input values and handle blank/missing cells.
Assumption: replace lowercase and uppercase vowels, preserving uppercase where possible is an optional variation. The following example replaces lowercase vowels and is easy to extend.
POM is a design pattern in which each page/component has a class encapsulating its locators and operations. Tests call business-level methods instead of repeating low-level locators. This improves reuse and maintainability.
Similar to Question 12. State your level, then support it with OOP, collections, exception handling, strings, file handling, test utilities, and examples of code you maintain. Avoid a rating you cannot demonstrate.
The exact pattern was not included in the question list, so an exact solution cannot be determined. For example, a right triangle of stars can be printed with nested loops:.
The code snippet was not included, so the output cannot be determined. In an interview, trace variable values line by line, evaluate operator precedence, identify static vs instance dispatch, and consider loop boundaries and exception flow. Provide the actual snippet for an exact output.
• Encapsulation: hide internal state and expose controlled methods. • Abstraction: expose essential behavior while hiding implementation details. • Inheritance: reuse/extend behavior from a superclass. • Polymorphism: same interface/base type can refer to different implementations. In Selenium, WebDriver is an interface implemented by browser-specific drivers; page objects encapsulate locators and actions.
Java does not support user-defined operator overloading for classes. The + operator is built in for numeric addition and String concatenation, but developers cannot redefine + for a custom class.
Common conceptual types: single, multilevel, hierarchical, multiple, and hybrid. Java classes support single, multilevel, and hierarchical inheritance through classes. Multiple/hybrid inheritance of type can be modeled using interfaces; a class cannot extend two classes.
TestNG is a Java test framework used to define, organize, parameterize, and execute tests. Review the annotations in Question 19 and the attributes in Question 7.
Configure TestNG with parallel and thread-count in testng.xml or use invocationCount/threadPoolSize for method invocations. Isolate WebDriver per test/thread (commonly ThreadLocal in a carefully designed framework) and isolate test data to avoid race conditions. <suite name="Suite" parallel="methods" thread-count="3"> <test name="UI"> <classes><class name="tests.LoginTest"/></classes> </test> </suite>.
The term depends on the framework. In Cucumber, a TestRunner is commonly a class configured with @CucumberOptions and a JUnit/TestNG runner to locate feature files, glue code, tags, and plugins. In TestNG-only projects, testng.xml and the TestNG engine select and run tests; there may not be a class literally named TestRunner. @RunWith(Cucumber.class) // JUnit-based example @CucumberOptions( features = "src/test/resources/features", glue = "stepdefinitions", plugin = {"pretty", "html:target/cucumber.html"} ).
Dynamic XPath handles changing attributes by using stable parts, text, or relationships. Validate uniqueness.
Prefer stable attributes such as name, aria-label, data-testid, visible text, or a stable parent/child relationship. If the ID has a stable prefix/suffix, use starts-with() or contains(). Avoid relying on a random ID or position alone. By field = By.xpath("//input.
String is immutable: once created, its character sequence cannot change. Operations such as replace/concat return a new String. Immutability supports safe sharing, predictable hashing, and String pool reuse. Use StringBuilder for repeated modifications in a single thread.
See Question 14. The key interfaces are List, Set, Queue/Deque, and Map (Map is part of the collections framework but does not extend Collection).
• NoSuchElementException: locator did not find a matching element. • StaleElementReferenceException: DOM changed after the element was located. • TimeoutException: wait condition did not become true in time. • ElementClickInterceptedException: another element/overlay intercepted the click. • ElementNotInteractableException: element is present but not interactable. • InvalidSelectorException: malformed CSS/XPath. • NoSuchFrameException: requested frame not found. • SessionNotCreatedException: browser/driver/session setup issue. Diagnose the underlying cause; use explicit waits, stable locators, frame/window switching, and compatible browser configuration rather than indiscriminately retrying.
This appears to be a section heading rather than a question. Use it to organize the following framework and coding topics during preparation.
Wrapper methods are reusable functions that wrap common Selenium operations with consistent waits, logging, and error handling. Examples might include clickElement(), enterText(), selectByVisibleText(), waitForVisible(), and captureScreenshot(). Avoid creating wrappers that hide useful failure details. public void clickWhenReady(By locator) {.
Separate test logic from test data. Store data in Excel/CSV/JSON/database or TestNG DataProvider; feed each data row to the same test method and validate each result. Use unique test data where tests modify application state and avoid embedding secrets in files.
Apache POI can read .xls and .xlsx. WorkbookFactory.create() detects supported workbook formats. Use DataFormatter to obtain displayed cell values and try-with-resources to close resources. try (FileInputStream in = new FileInputStream("testdata.xlsx"); Workbook workbook = WorkbookFactory.create(in)) { Sheet sheet = workbook.getSheet("Login"); DataFormatter formatter = new DataFormatter();.
• Array has fixed length after creation and can store primitives or references. • ArrayList is a resizable List of objects (primitives use wrapper types), supports methods such as add/remove, and allows duplicates.
Catch an exception when you can recover, add context, or translate it into a meaningful failure. Do not swallow it. Use specific exception types, preserve the original cause, and use finally/try-with-resources for cleanup. try {.
A traditional for loop has initialization, a condition, and an update. Initialization runs once; the condition is checked before each iteration; the body runs if true; then the update runs.
Windows/tabs use getWindowHandle(s) and switchTo().window(handle); JavaScript alerts use switchTo().alert(). Do not mix these APIs.
Save the original handle, wait for a new handle, compare the set, switch to the new context, and return to the original when finished. A browser tab is treated as a separate WebDriver window handle.
See Question 37. Immutability improves safe sharing, stable hash codes, predictable behavior, and string-pool reuse. Use StringBuilder for repeated string modifications.
static can be used for fields, methods, initialization blocks, and nested classes. A static field has one class-level copy shared by instances; a static method can be called through the class name and cannot directly access instance members without an object.
See Questions 1 and 3. Constructors initialize objects and dependencies; in a page object, passing WebDriver through the constructor helps every page use the same session.
A deadlock occurs when threads wait indefinitely for locks held by each other. For example, thread 1 holds lock A and waits for B, while thread 2 holds B and waits for A. Prevent it by acquiring locks in a consistent order, reducing nested locking, using timed locks where suitable, and avoiding unnecessary shared mutable state.
Map stores key-value pairs; keys are unique, values may repeat. HashMap has no guaranteed order, LinkedHashMap preserves insertion order, and TreeMap sorts keys.
Selenium Grid runs WebDriver tests on remote browser instances and supports parallel execution across browsers, versions, and operating systems. A test sends WebDriver commands to Grid, which routes them to a suitable node/browser session. Grid 4 supports standalone, hub/node, and distributed configurations. A single machine can run Grid in standalone mode; browser availability and machine resources still limit concurrency.