Automation - Q&A Set 3

Expert level automation questions

Java-Oriented Questions

Essential Java concepts frequently asked in automation interviews.

Q1: == vs .equals() in Java

Question

Difference between == and .equals() in Java. Give examples.

Examples

// Primitives - == compares values
int a = 10, b = 10;
System.out.println(a == b); // true

// Strings
String s1 = "Hello";
String s2 = "Hello";
String s3 = new String("Hello");

System.out.println(s1 == s2);        // true (same reference in String pool)
System.out.println(s1 == s3);        // false (different objects)
System.out.println(s1.equals(s3));   // true (same content)

Best Practice

Always use .equals() for object comparison. Override equals() in custom classes for proper comparison.

Q2: HashMap vs Hashtable vs ConcurrentHashMap

Question

Explain HashMap vs Hashtable vs ConcurrentHashMap.

Comparison Table

Feature              | HashMap         | Hashtable       | ConcurrentHashMap
---------------------+-----------------+-----------------+------------------
Thread Safety        | No              | Yes             | Yes
Null Keys/Values     | Allowed         | Not allowed     | Not allowed
Performance          | Fast            | Slow            | Fast
Synchronization      | Not synchronized| Synchronized    | Segment locking
Legacy               | No              | Yes             | No

Usage Examples

// HashMap - Not thread-safe
Map<String, Integer> hashMap = new HashMap<>();
hashMap.put("A", 1);
hashMap.put(null, 2); // Allows null

// Hashtable - Thread-safe but slow
Map<String, Integer> hashtable = new Hashtable<>();
hashtable.put("A", 1);
// hashtable.put(null, 2); // Throws NullPointerException

// ConcurrentHashMap - Thread-safe and fast
Map<String, Integer> concurrentMap = new ConcurrentHashMap<>();
concurrentMap.put("A", 1);
// concurrentMap.put(null, 2); // Throws NullPointerException

When to Use

HashMap for single-threaded, ConcurrentHashMap for multi-threaded applications. Avoid Hashtable (legacy).

Q3: ArrayList vs LinkedList

Question

What is the difference between ArrayList and LinkedList? When would you use which?

Usage

// ArrayList - Use for frequent access
List<String> arrayList = new ArrayList<>();
arrayList.add("A");
String element = arrayList.get(0); // O(1)

// LinkedList - Use for frequent add/remove
List<String> linkedList = new LinkedList<>();
linkedList.add(0, "A"); // O(1) at beginning
linkedList.remove(0);   // O(1) at beginning

Q4: final, finally, and finalize()

Question

Explain final, finally, and finalize() with examples.

Examples

// final keyword
final int MAX_VALUE = 100;
// MAX_VALUE = 200; // Compilation error

final class FinalClass { } // Cannot be extended

// finally block
try {
    // risky code
} catch (Exception e) {
    // handle exception
} finally {
    // Always executes - cleanup code
    System.out.println("Cleanup");
}

// finalize() - deprecated
@Override
protected void finalize() throws Throwable {
    // Called before GC (don't rely on this)
}

Q5: Palindrome Check in Java

Question

Write a Java program to check if a string is a palindrome.

Implementation

public class PalindromeChecker {

    // Method 1: Using two pointers
    public static boolean isPalindrome(String str) {
        str = str.toLowerCase().replaceAll("[^a-z0-9]", "");
        int left = 0, right = str.length() - 1;

        while (left < right) {
            if (str.charAt(left) != str.charAt(right)) {
                return false;
            }
            left++;
            right--;
        }
        return true;
    }

    // Method 2: Using StringBuilder
    public static boolean isPalindromeReverse(String str) {
        String cleaned = str.toLowerCase().replaceAll("[^a-z0-9]", "");
        String reversed = new StringBuilder(cleaned).reverse().toString();
        return cleaned.equals(reversed);
    }
}

Q6: String Pool in Java

Question

Explain the concept of String Pool in Java.

String Pool is a special memory region in heap where Java stores string literals to optimize memory by reusing immutable strings.

String Pool Examples

// String literals go to pool
String s1 = "Hello";
String s2 = "Hello";
System.out.println(s1 == s2); // true (same reference)

// new String() creates object in heap
String s3 = new String("Hello");
System.out.println(s1 == s3); // false (different reference)

// intern() moves to pool
String s4 = s3.intern();
System.out.println(s1 == s4); // true (same reference)

Key Point

String pool saves memory by reusing string literals. Use intern() to move strings to pool.

Q7: Checked vs Unchecked Exceptions

Question

What are checked and unchecked exceptions? Give examples.

Examples

// Checked Exception - Must handle
public void readFile() throws IOException {
    FileReader file = new FileReader("test.txt");
}

// Or use try-catch
try {
    FileReader file = new FileReader("test.txt");
} catch (IOException e) {
    e.printStackTrace();
}

// Unchecked Exception - Optional to handle
int[] arr = {1, 2, 3};
System.out.println(arr[5]); // ArrayIndexOutOfBoundsException

String str = null;
System.out.println(str.length()); // NullPointerException

Q8: Static Keyword in Java

Question

Explain static keyword with different use cases.

Static Keyword Uses

public class StaticExample {

    // 1. Static variable - shared across all instances
    static int count = 0;

    // 2. Static method - can be called without object
    public static void displayCount() {
        System.out.println("Count: " + count);
    }

    // 3. Static block - executes once when class loads
    static {
        System.out.println("Static block executed");
        count = 10;
    }

    // 4. Static nested class
    static class NestedClass {
        void display() {
            System.out.println("Static nested class");
        }
    }
}

// Usage
StaticExample.displayCount(); // No object needed
StaticExample.count = 5;

Key Point

Static members belong to class, not instances. Useful for utility methods, constants, and counters.

Q9: throw vs throws

Question

Difference between throw and throws.

Examples

// throw - explicitly throw exception
public void validateAge(int age) {
    if (age < 18) {
        throw new IllegalArgumentException("Age must be 18+");
    }
}

// throws - declare exception in signature
public void readFile(String path) throws IOException {
    FileReader file = new FileReader(path);
}

// Can declare multiple exceptions
public void process() throws IOException, SQLException {
    // method body
}

Q10: Remove Duplicates from Array

Question

Write a Java program to remove duplicates from an array.

Implementation

// Method 1: Using HashSet
public static int[] removeDuplicates(int[] arr) {
    Set<Integer> set = new LinkedHashSet<>();
    for (int num : arr) {
        set.add(num);
    }
    return set.stream().mapToInt(Integer::intValue).toArray();
}

// Method 2: Using Stream API
public static int[] removeDuplicatesStream(int[] arr) {
    return Arrays.stream(arr).distinct().toArray();
}

// Usage
int[] arr = {1, 2, 2, 3, 4, 4, 5};
int[] result = removeDuplicates(arr);
// Output: {1, 2, 3, 4, 5}

Selenium-Oriented Questions

Selenium WebDriver concepts for automation testing interviews.

Q11: findElement() vs findElements()

Question

Difference between findElement() and findElements().

Examples

// findElement() - Returns single element
WebElement element = driver.findElement(By.id("username"));
element.sendKeys("test");

// findElements() - Returns list
List<WebElement> elements = driver.findElements(By.className("menu-item"));
System.out.println("Total elements: " + elements.size());

// Check if element exists
if (driver.findElements(By.id("optional")).size() > 0) {
    // Element exists
}

Q12: Handling Dynamic Web Elements

Question

How do you handle dynamic web elements in Selenium?

Implementation

// Wait for element to be clickable
WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));
WebElement element = wait.until(
    ExpectedConditions.elementToBeClickable(By.id("dynamic-btn")));

// Dynamic XPath
String xpath = "//button[contains(@id, 'submit')]";
driver.findElement(By.xpath(xpath)).click();

// Handle stale element
for (int i = 0; i < 3; i++) {
    try {
        driver.findElement(By.id("element")).click();
        break;
    } catch (StaleElementReferenceException e) {
        // Retry
    }
}

Q13: Types of Waits in Selenium

Question

Explain different types of waits in Selenium (implicit, explicit, fluent).

Wait Types

// 1. Implicit Wait - Global setting
driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(10));

// 2. Explicit Wait - Specific conditions
WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));
WebElement element = wait.until(
    ExpectedConditions.elementToBeClickable(By.id("submit")));

// 3. Fluent Wait - Custom polling and exceptions
FluentWait<WebDriver> fluentWait = new FluentWait<>(driver)
    .withTimeout(Duration.ofSeconds(30))
    .pollingEvery(Duration.ofSeconds(2))
    .ignoring(NoSuchElementException.class);

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

Q14: Dropdown Selection in Selenium

Question

Write a code snippet to select a value from a dropdown using Selenium.

Using Select Class

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

// Select by visible text
dropdown.selectByVisibleText("India");

// Select by value
dropdown.selectByValue("IN");

// Select by index
dropdown.selectByIndex(2);

// Get selected option
WebElement selected = dropdown.getFirstSelectedOption();
System.out.println(selected.getText());

Q15: File Uploads and Downloads

Question

How do you handle file uploads and downloads in Selenium?

File Upload

// File Upload - sendKeys to input element
WebElement uploadElement = driver.findElement(By.id("fileUpload"));
uploadElement.sendKeys("C:/path/to/file.txt");

File Download

// Set download directory in Chrome
ChromeOptions options = new ChromeOptions();
Map<String, Object> prefs = new HashMap<>();
prefs.put("download.default_directory", "C:/downloads");
options.setExperimentalOption("prefs", prefs);

WebDriver driver = new ChromeDriver(options);

// Verify file downloaded
File file = new File("C:/downloads/report.pdf");
Assert.assertTrue(file.exists());

Q16: Handling Alerts in Selenium

Question

Explain how to handle alerts, confirmation, and prompt pop-ups in Selenium.

Alert Handling

// Simple Alert
Alert alert = driver.switchTo().alert();
System.out.println(alert.getText());
alert.accept(); // Click OK

// Confirmation Alert
alert.dismiss(); // Click Cancel

// Prompt Alert
alert.sendKeys("Text input");
alert.accept();

// Wait for alert
WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));
wait.until(ExpectedConditions.alertIsPresent());
driver.switchTo().alert().accept();

Q17: XPath for Table Rows

Question

Write XPath to select the 3rd row of a table where column value = “Approved”.

XPath Solution

// Select 3rd row where any column contains "Approved"
//table//tr[td[text()='Approved']][3]

// Select 3rd row where specific column (e.g., 4th column) = "Approved"
//table//tr[td[4][text()='Approved']][3]

// More robust with contains
//table//tr[td[contains(text(), 'Approved')]][3]

// Java implementation
WebElement thirdRow = driver.findElement(
    By.xpath("//table//tr[td[text()='Approved']][3]"));

Q18: Relative vs Absolute XPath

Question

Difference between relative and absolute XPath. Which one do you prefer?

Examples

// Absolute XPath - Avoid
/html/body/div[1]/div[2]/form/input[1]

// Relative XPath - Preferred
//input[@id='username']
//form[@id='loginForm']//input[@name='username']

Recommendation

Always use relative XPath for better maintainability and resilience to DOM changes.

Q19: Multiple Windows/Tabs Handling

Question

How do you handle multiple browser windows/tabs in Selenium?

Window Handling

// Get current window handle
String mainWindow = driver.getWindowHandle();

// Get all window handles
Set<String> allWindows = driver.getWindowHandles();

// Switch to new window
for (String window : allWindows) {
    if (!window.equals(mainWindow)) {
        driver.switchTo().window(window);
        // Perform actions in new window
        driver.close();
    }
}

// Switch back to main window
driver.switchTo().window(mainWindow);

Q20: Screenshot on Test Failure

Question

How do you capture a screenshot on test failure?

Screenshot Capture

// Method to capture screenshot
public String captureScreenshot(String testName) {
    TakesScreenshot ts = (TakesScreenshot) driver;
    File source = ts.getScreenshotAs(OutputType.FILE);
    String dest = "screenshots/" + testName + ".png";
    FileUtils.copyFile(source, new File(dest));
    return dest;
}

// In TestNG
@AfterMethod
public void tearDown(ITestResult result) {
    if (result.getStatus() == ITestResult.FAILURE) {
        captureScreenshot(result.getName());
    }
}

Framework & Automation Questions

Test automation framework design and best practices.

Q21: Framework Types

Question

Difference between Data-Driven, Keyword-Driven, and Hybrid frameworks.

Concepts

// Data-Driven: Test data in Excel
@Test(dataProvider = "loginData")
public void testLogin(String user, String pass) {
    loginPage.login(user, pass);
}

// Keyword-Driven: Excel with keywords
// KEYWORD    | LOCATOR      | VALUE
// navigate   | url          | https://example.com
// click      | id=login     | 
// sendKeys   | id=username  | admin

// Hybrid: Combines both approaches

Q22: Test Data Management

Question

How do you manage test data in your automation framework?

Implementation

// Excel utility
public class ExcelUtils {
    public static Object[][] getTestData(String sheetName) {
        // Read Excel and return 2D array
    }
}

// Usage with DataProvider
@DataProvider(name = "testData")
public Object[][] getData() {
    return ExcelUtils.getTestData("LoginData");
}

@Test(dataProvider = "testData")
public void test(String username, String password) {
    // Test implementation
}

Q23: Logging in Selenium Framework

Question

How do you implement logging in Selenium framework? Which library do you prefer?

Log4j2 Implementation

// Using Log4j2
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

public class BaseTest {
    private static Logger logger = LogManager.getLogger(BaseTest.class);

    @Test
    public void testLogin() {
        logger.info("Starting login test");
        logger.debug("Entering credentials");
        logger.error("Login failed");
        logger.warn("Slow response time");
    }
}

Preference

Log4j2 is preferred for performance. SLF4J is good as a facade over different logging frameworks.

Q24: Test Parameterization in TestNG

Question

How do you parameterize test cases in TestNG?

Parameterization Methods

// Method 1: Using @Parameters from XML
@Test
@Parameters({"username", "password"})
public void testLogin(String user, String pass) {
    // Test logic
}

// Method 2: Using @DataProvider
@DataProvider(name = "credentials")
public Object[][] getCredentials() {
    return new Object[][] {
        {"user1", "pass1"},
        {"user2", "pass2"}
    };
}

@Test(dataProvider = "credentials")
public void testLogin(String user, String pass) {
    // Test logic
}

Q25: Parallel Execution

Question

How do you implement parallel execution in TestNG or JUnit?

testng.xml Configuration

<suite name="ParallelSuite" parallel="methods" thread-count="3">
    <test name="Tests">
        <classes>
            <class name="com.tests.LoginTest"/>
        </classes>
    </test>
</suite>

<!-- parallel options: methods, tests, classes -->

Q26: Cross-Browser Testing

Question

How do you design a framework to handle cross-browser testing?

DriverFactory Pattern

public class DriverFactory {
    public static WebDriver createDriver(String browser) {
        switch(browser.toLowerCase()) {
            case "chrome":
                return new ChromeDriver();
            case "firefox":
                return new FirefoxDriver();
            case "edge":
                return new EdgeDriver();
            default:
                return new ChromeDriver();
        }
    }
}

// TestNG XML with parameters
@BeforeMethod
@Parameters("browser")
public void setup(String browser) {
    driver = DriverFactory.createDriver(browser);
}

Q27: Custom Reports

Question

How do you generate custom reports in your framework?

Extent Reports Setup

public class ExtentManager {
    private static ExtentReports extent;

    public static ExtentReports getInstance() {
        if (extent == null) {
            extent = new ExtentReports();
            ExtentSparkReporter spark =
                new ExtentSparkReporter("reports/report.html");
            extent.attachReporter(spark);
        }
        return extent;
    }
}

Q28: Retry Failed Tests

Question

Explain how you handle retries for failed test cases.

Retry Analyzer

public class RetryAnalyzer implements IRetryAnalyzer {
    private int count = 0;
    private int maxRetry = 2;

    @Override
    public boolean retry(ITestResult result) {
        if (count < maxRetry) {
            count++;
            return true;
        }
        return false;
    }
}

// Use in test
@Test(retryAnalyzer = RetryAnalyzer.class)
public void testMethod() {
    // Test logic
}

Q29: Jenkins CI/CD Integration

Question

Explain how you integrated your framework with CI tools like Jenkins.

Maven Command

mvn clean test -Dsuite=testng.xml -Dbrowser=chrome

Q30: Framework Maintainability & Scalability

Question

How do you ensure maintainability and scalability of your framework?

Framework Architecture

Key Design Principles:

1. Separation of Concerns
   - Tests separate from page objects
   - Utils separate from business logic

2. DRY (Don't Repeat Yourself)
   - Reusable methods in base classes
   - Common utilities centralized

3. Configuration Management
   - Properties files for environments
   - Easy switching between DEV/QA/PROD

4. Robust Error Handling
   - Try-catch blocks with meaningful messages
   - Retry logic for flaky tests

5. Comprehensive Reporting
   - Detailed logs and screenshots
   - Executive summary reports

Golden Rule

If you need to change the same code in multiple places, it needs refactoring. Design for change from day one.