[go: up one dir, main page]

0% found this document useful (0 votes)
85 views67 pages

Interview Question Part - 1

Interview Question and answer

Uploaded by

ranjeet kumar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
85 views67 pages

Interview Question Part - 1

Interview Question and answer

Uploaded by

ranjeet kumar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 67

1. Open any eCommerce website and find the XPath of the search bar.

For example, if I open Amazon's homepage, the XPath for the search bar can be:

bash

Copy code

//input[@id='twotabsearchtextbox']

I locate the search bar using the id attribute in the HTML. However, if this doesn't work, I
can create a more robust XPath based on its position in the DOM or other attributes like
this:

//input[@type='text' and @aria-label='Search']

2. What are the locators you will use in your project?

In my projects, I commonly use the following locators:

1. ID: Best for unique elements, quick and reliable.

2. Name: Used when an element has a name attribute.

3. ClassName: Locates elements using the class attribute.

4. XPath: Powerful but can be slower; used for complex DOM hierarchies.

5. CSS Selector: Lightweight and faster than XPath in some cases.

6. LinkText/PartialLinkText: Used for identifying hyperlinks based on text.

3. Have you ever used CSS Selectors?

Yes, I use CSS selectors for faster and more efficient element identification, especially
when the element's ID or Name is not available. For example:

input#username

input[type='text'][name='username']

4. Types of XPath?

1. Absolute XPath: Starts from the root of the HTML DOM tree. Example:
/html/body/div/header/input

1|Inter view Qu estion and A nswer part 1


o Less reliable since small changes in the DOM can break the XPath.

2. Relative XPath: Starts from any element in the DOM. Example:


//input[@id='search']

o More flexible and widely used.

5. Difference between Background and Scenario Outline in the Cucumber


Framework.

• Background: This is used to define steps common to all scenarios in a feature


file. It runs before each scenario.

o Example: Login functionality before accessing other features.

• Scenario Outline: This is used when you need to run the same scenario with
different sets of data.

o Example: Testing login with multiple username-password combinations


using a data table.

6. Have you used OOPS concepts in the Cucumber framework?

Yes, I have applied OOPS concepts such as:

• Encapsulation: By creating Page Object Model (POM) classes that encapsulate


web element interactions.

• Inheritance: Sharing common step definitions or utility methods in a base class.

• Polymorphism: Overriding methods in different classes to handle different


scenarios in the framework.

• Abstraction: Using interfaces and abstract classes for better test design and
reusability.

7. Open the online compiler, create a string, enter some words (e.g., "This is a Java
Program"), remove the space, print it, and reverse the string. Explain the program.

public class StringManipulation {

public static void main(String[] args) {

String str = "This is a Java Program";

2|Inter view Qu estion and A nswer part 1


// Remove spaces

String noSpaceStr = str.replaceAll("\\s", "");

System.out.println("Without Spaces: " + noSpaceStr);

// Reverse the string

String reversedStr = new StringBuilder(noSpaceStr).reverse().toString();

System.out.println("Reversed String: " + reversedStr);

• Explanation: First, the program removes all spaces using replaceAll("\\s", "").
Then, it reverses the string using StringBuilder and prints both the space-free and
reversed strings.

8. SDLC Lifecycle.

SDLC stands for Software Development Life Cycle. The stages include:

1. Requirement Gathering and Analysis: Understanding what needs to be


developed.

2. Design: Planning the architecture and design of the software.

3. Implementation/Coding: Developers write the actual code.

4. Testing: Testers verify the software to ensure it meets the requirements and is
free of defects.

5. Deployment: The software is released to users.

6. Maintenance: Post-release support and updates.

9. How will you prioritize the methods in TestNG? If two methods have the same
priority, which one will execute first?

In TestNG, you can prioritize methods using the priority attribute in the @Test
annotation. If two methods have the same priority, TestNG will execute them in the
order they appear in the class.

3|Inter view Qu estion and A nswer part 1


@Test(priority = 1)

public void testMethod1() { }

@Test(priority = 2)

public void testMethod2() { }

10. Different types of exceptions you faced in your projects.

• NoSuchElementException: When an element is not found on the webpage.

• ElementNotInteractableException: When an element is present but not


interactable (e.g., hidden or disabled).

• TimeoutException: When a command takes longer than expected to execute.

• NullPointerException: When trying to access an object that has not been


initialized.

11. How to handle exceptions?

In Java, I handle exceptions using:

• try-catch blocks: To catch exceptions and handle them gracefully.

• throw/throws keywords: To propagate exceptions upwards.

• Custom Exceptions: For more specific exception handling scenarios.

• Finally block: To ensure cleanup actions, like closing resources, always run.

12. How to handle pop-ups in Selenium?

I handle pop-ups using:

1. Alert Handling:

Alert alert = driver.switchTo().alert();

alert.accept(); // for OK

alert.dismiss(); // for Cancel

2. Window Handling: For handling new browser windows or tabs:

driver.switchTo().window(windowHandle);
4|Inter view Qu estion and A nswer part 1
13. Explain the folder structure of your framework.

Typically, my framework follows this structure:

• src/main/java: Contains core classes, utilities, and POM classes.

• src/test/java: Contains test cases, test data, and TestNG files.

• src/resources: Contains configuration files (e.g., config.properties, log4j.xml).

• test-output: Holds TestNG reports.

• pom.xml: The Maven configuration file that manages dependencies.

14. Explain the pom.xml file.

The pom.xml file is the configuration file for Maven projects. It contains:

• Project coordinates: Group ID, Artifact ID, Version.

• Dependencies: Lists libraries like Selenium, Appium, TestNG, etc.

• Plugins: Defines build plugins for tasks like packaging and reporting.

• Profiles: Allows running different configurations for different environments.

15. Have you ever done cross-browser testing? How do you do that?

Yes, I've done cross-browser testing using Selenium and tools like BrowserStack. In
Selenium, I initialize the WebDriver based on the browser:

if (browser.equals("chrome")) {

System.setProperty("webdriver.chrome.driver", "path to chrome driver");

driver = new ChromeDriver();

} else if (browser.equals("firefox")) {

System.setProperty("webdriver.gecko.driver", "path to gecko driver");

driver = new FirefoxDriver();

This allows testing on multiple browsers (e.g., Chrome, Firefox, Edge).

5|Inter view Qu estion and A nswer part 1


16. What are the different types of testing you have done so far?

I have experience in:

• Functional Testing

• Regression Testing

• Smoke Testing

• Cross-browser Testing

• API Testing (using REST Assured)

• Mobile Testing (using Appium)

• Performance Testing (using JMeter)

17. Difference between Smoke Testing and Regression Testing.

• Smoke Testing: A quick test to ensure that the basic functionality of the
application is working. It's performed after every build.

• Regression Testing: Thorough testing of the entire application to ensure that


new changes haven't broken any existing functionality.

18. Have you used collections in your scripts?

Yes, I frequently use Java collections like:

• ArrayList: For dynamically sized arrays.

• HashMap: For key-value pairs, especially for storing test data.

• Set: For ensuring unique data (e.g., no duplicate values).

19. Have you created a framework from scratch?

Yes, I have created multiple automation frameworks from scratch. I typically use a
combination of:

• Selenium for web automation.

• Appium for mobile automation.

• TestNG for test execution.

• Maven for build management.

6|Inter view Qu estion and A nswer part 1


• Page Object Model (POM) for maintaining separation between test logic and
element locators.

20. How is HashMap used in Java projects?

HashMap in Java is used to store data in key-value pairs. It is particularly useful when
you need fast access to data based on a specific key. In automation projects, I use
HashMap to store test data, configuration properties, or even web element locators. For
example, in a framework, you could store device details for multiple connected devices,
where the key could be the device ID, and the value could be its details (e.g., platform,
version).

Example:

HashMap<String, String> deviceDetails = new HashMap<>();

deviceDetails.put("Device1", "Android");

deviceDetails.put("Device2", "iOS");

21. How are Collections in Java used within a project?

Java Collections are used to manage groups of objects, and they provide several utility
classes like ArrayList, HashMap, HashSet, LinkedList, etc. In automation projects,
collections are used to manage test data, maintain lists of elements, and manage
configuration or result sets.

Examples:

• ArrayList: Used to store a dynamic list of test data values.

• HashMap: Used to store key-value pairs such as login credentials or


environment-specific configurations.

• HashSet: Used to store unique test data, such as a list of user IDs.

22. How will you ensure all test cases for the Login page have passed?

To ensure all test cases for the Login page have passed:

1. Use Assertions: I validate each critical element, such as username/password


fields and the login button, to ensure they are working as expected.

2. Use Reporting: Utilize a reporting framework like Extent Reports or Allure to


generate detailed reports after test execution, which shows pass/fail status for
all test cases.

7|Inter view Qu estion and A nswer part 1


3. Check Logs: Review logs for errors or exceptions that could indicate test
failures.

4. Review TestNG/JUnit results: The final output of TestNG/JUnit gives a summary


of the test cases, showing which ones have passed or failed.

5. Automation Framework: Build a comprehensive login page test suite and


execute it using a CI tool like Jenkins, where reports are generated and failures
are flagged.

23. Write a Java program to find the number of occurrences of a specific character
in your name.

public class CharacterCount {

public static void main(String[] args) {

String name = "RanjeetKumar";

char specificChar = 'e';

int count = 0;

for (int i = 0; i < name.length(); i++) {

if (name.charAt(i) == specificChar) {

count++;

System.out.println("Occurrences of '" + specificChar + "' in the name: " + count);

• Explanation: This program loops through each character in the string


"RanjeetKumar" and increments a counter whenever the character matches 'e'. It
then prints the total count of occurrences.

24. Write XPath expressions to capture all the language occurrences on a


Wikipedia page.

8|Inter view Qu estion and A nswer part 1


The XPath to capture all the language options (from the language sidebar) on a
Wikipedia page can be:

//div[@id='p-lang']//a

This XPath expression navigates to the sidebar where languages are listed (id='p-lang')
and selects all anchor tags (<a> elements), which typically represent the language links.

25. Explain the role of Constructors in Java and their purpose.

Constructors in Java are special methods used to initialize objects. They are called
when an object of a class is created. The primary role of constructors is to set the initial
state of the object or to provide initial values to instance variables.

• Types:

o Default Constructor: If no constructor is defined, Java provides a default


constructor.

o Parameterized Constructor: Allows passing arguments to initialize an


object with specific values.

Example:

public class User {

String username;

int age;

// Parameterized constructor

public User(String username, int age) {

this.username = username;

this.age = age;

7. How would you swap two values without using a third variable?

public class SwapValues {

public static void main(String[] args) {

9|Inter view Qu estion and A nswer part 1


int a = 5, b = 10;

// Swapping without a third variable

a = a + b; // a becomes 15

b = a - b; // b becomes 5

a = a - b; // a becomes 10

System.out.println("After swapping: a = " + a + ", b = " + b);

• Explanation: The values of a and b are swapped using arithmetic operations


without the need for a third variable.

26. What are the different data types in Java?

Java has two categories of data types:

1. Primitive Data Types:

o byte, short, int, long: Integer types.

o float, double: Floating-point types.

o char: Character type.

o boolean: Represents true/false values.

2. Non-Primitive Data Types (Reference Types):

o String: Represents a sequence of characters.

o Arrays: Used to store multiple values of the same type.

o Classes and Objects: Represent user-defined types.

o Interfaces: Used to define abstract types.

27. How do you utilize an Object Repository in your automation framework?

In automation, an Object Repository is a centralized location where all web elements


and their locators are stored. It helps in managing web elements efficiently. I utilize the
10 | I n t e r v i e w Q u e s t i o n a n d A n s w e r p a r t 1
Object Repository to separate the locators from the test scripts, improving
maintainability.

I usually implement the Object Repository using:

1. Page Object Model (POM): Where each page of the application has its own class
with locators and methods to interact with the elements.

2. Properties File: I store element locators in a .properties file and fetch them
during runtime.

Example of Properties File:

login.username = //input[@id='username']

login.password = //input[@id='password']

28. What essential Git commands do you use, and how do you merge code using
Git?

The essential Git commands I use are:

1. git clone: To clone a repository to my local machine.

2. git status: To check the current state of the working directory.

3. git add .: To stage all changes for the next commit.

4. git commit -m "message": To commit the staged changes with a message.

5. git pull: To fetch and merge changes from the remote repository to the local
branch.

6. git push: To push committed changes to the remote repository.

Merging code using Git:

• git checkout master: Switch to the master branch.

• git pull origin master: Pull the latest changes from the remote master branch.

• git checkout feature_branch: Switch to the feature branch.

• git merge master: Merge the master branch into the feature branch.

• git push origin feature_branch: Push the merged changes back to the remote
feature branch.

11 | I n t e r v i e w Q u e s t i o n a n d A n s w e r p a r t 1
29. What is Collections in Java?

The Collections framework in Java is a set of classes and interfaces that provide data
structures to store and manipulate groups of objects. It includes interfaces such as
List, Set, Queue, and classes like ArrayList, HashSet, LinkedList, and HashMap. The
framework provides methods to perform operations like searching, sorting, insertion,
manipulation, and deletion of elements.

30. How many listeners are there in TestNG?

TestNG provides several types of listeners to listen to different events in the lifecycle of
a test execution. Some key listeners include:

1. ITestListener: Listens to test case events (start, success, failure, etc.).

2. ISuiteListener: Listens to suite execution events (before and after suite


execution).

3. IExecutionListener: Listens to the start and finish of test execution.

4. IReporter: Used to generate customized reports.

5. IAnnotationTransformer: Used to modify annotations at runtime (e.g., @Test).

6. IInvokedMethodListener: Listens to individual method invocations.

31. What is the difference between String, StringBuffer, and StringBuilder?

1. String:

o Immutable (cannot be changed after creation).

o Thread-safe due to immutability.

o Suitable for small operations with constant strings.

2. StringBuffer:

o Mutable (can be changed after creation).

o Thread-safe as all methods are synchronized.

o Suitable for use in multithreaded environments.

3. StringBuilder:

o Mutable.

12 | I n t e r v i e w Q u e s t i o n a n d A n s w e r p a r t 1
o Not thread-safe (faster than StringBuffer in single-threaded
environments).

o Suitable for scenarios where synchronization is not needed.

32. What are REST API status codes?

REST APIs use status codes to indicate the result of an HTTP request. Some common
codes include:

• 200 OK: The request was successful.

• 201 Created: A resource has been created successfully.

• 400 Bad Request: The request is invalid or cannot be processed.

• 401 Unauthorized: Authentication is required.

• 403 Forbidden: The request is valid, but the server is refusing action.

• 404 Not Found: The requested resource is not found.

• 500 Internal Server Error: The server encountered an error.

33. How do you schedule a job in Jenkins for midnight?

To schedule a job in Jenkins to run at midnight, you use the Build Triggers section and
specify the cron-like syntax. The cron expression for midnight would be:

Copy code

00***

This expression means:

• 0 minutes

• 0 hours (midnight)

• * * *: Every day, every month, every day of the week.

34. Write a code to move all zeros to the beginning of this array: {6, 8, 7, 0, 5, 0, 3, 0}.

public class MoveZeros {

public static void main(String[] args) {

int[] arr = {6, 8, 7, 0, 5, 0, 3, 0};

13 | I n t e r v i e w Q u e s t i o n a n d A n s w e r p a r t 1
int n = arr.length;

int[] result = new int[n];

int index = n - 1;

for (int i = n - 1; i >= 0; i--) {

if (arr[i] != 0) {

result[index--] = arr[i];

// Print the result

for (int i : result) {

System.out.print(i + " ");

Output: 0 0 0 6 8 7 5 3

35. What are the differences between Python and Java?

1. Syntax:

o Python has simpler, more readable syntax.

o Java is more verbose with strict type declarations.

2. Performance:

o Java is generally faster due to being a compiled language.

o Python is interpreted and thus may be slower.

3. Typing:

o Python uses dynamic typing.

o Java uses static typing.

14 | I n t e r v i e w Q u e s t i o n a n d A n s w e r p a r t 1
4. Memory Management:

o Both use garbage collection, but Java provides more control over memory
allocation.

5. Use Cases:

o Python is often used for scripting, data science, and machine learning.

o Java is used for large-scale enterprise applications and Android


development.

36. How do you validate a JSON schema?

To validate a JSON schema in Java, you can use libraries like json-schema-validator
from everit or com.networknt. Here’s an example using everit:

import org.everit.json.schema.Schema;

import org.everit.json.schema.loader.SchemaLoader;

import org.json.JSONObject;

import org.json.JSONTokener;

public class JSONSchemaValidation {

public static void main(String[] args) {

JSONObject jsonSchema = new JSONObject(new JSONTokener(

JSONSchemaValidation.class.getResourceAsStream("/schema.json")));

JSONObject jsonData = new JSONObject(new JSONTokener(

JSONSchemaValidation.class.getResourceAsStream("/data.json")));

Schema schema = SchemaLoader.load(jsonSchema);

schema.validate(jsonData); // Throws ValidationException if invalid

15 | I n t e r v i e w Q u e s t i o n a n d A n s w e r p a r t 1
37. What is Karate framework?

Karate is an open-source API testing framework that allows users to write tests for HTTP
services. It is built on top of the Cucumber framework and uses the Gherkin syntax. It
supports BDD-style tests for REST APIs, SOAP APIs, and GraphQL APIs. Karate enables
easy integration of data-driven tests and validation of responses using JSON or XML
structures.

38. How can you reduce the runtime of an automation test?

1. Parallel Execution: Run tests in parallel to utilize multiple resources.

2. Selective Execution: Only execute critical or impacted test cases (e.g., via test
tags or priorities).

3. Optimizing Wait Times: Use explicit waits instead of thread.sleep to avoid


unnecessary waiting.

4. Headless Browser Execution: Use headless browser modes in Selenium (e.g.,


Chrome Headless) to reduce overhead.

5. Data-Driven Testing: Use efficient methods to input test data, avoiding


duplicate test runs.

6. Efficient Locators: Ensure element locators are precise to avoid slow or failing
tests.

39. How do you rerun failed test cases in TestNG?

To rerun failed test cases in TestNG, you can:

1. Use the testng-failed.xml file that is generated after a test suite run. This file
contains only the failed test cases, which can be rerun.

2. Implement an IAnnotationTransformer or IRetryAnalyzer interface to


automatically retry failed tests.

Example of IRetryAnalyzer:

public class RetryAnalyzer implements IRetryAnalyzer {

private int retryCount = 0;

private static final int maxRetryCount = 2;

16 | I n t e r v i e w Q u e s t i o n a n d A n s w e r p a r t 1
@Override

public boolean retry(ITestResult result) {

if (retryCount < maxRetryCount) {

retryCount++;

return true;

return false;

40. What are the new features in Java 8?

Some key features introduced in Java 8:

1. Lambda Expressions: Enable writing functional-style code.

2. Streams API: For processing collections of objects in a functional manner.

3. Functional Interfaces: Introduced @FunctionalInterface and predefined


interfaces like Predicate, Function, etc.

4. Default Methods: Allow interfaces to have methods with a default


implementation.

5. Optional: Used to avoid null pointer exceptions.

6. Date and Time API: A new java.time package for working with dates and times.

41. What is a Lambda expression in Java?

A Lambda expression is a way to write anonymous functions in Java. It provides a clear


and concise way to represent a method interface. It simplifies the syntax for functional
programming and makes the code more readable.

Example:

List<String> names = Arrays.asList("Ranjeet", "Kumar", "John");

names.forEach(name -> System.out.println(name));

17 | I n t e r v i e w Q u e s t i o n a n d A n s w e r p a r t 1
42. How do you schedule a Jenkins job for midnight?

To schedule a Jenkins job for midnight, use the following cron syntax in the Build
Triggers section:

00***

This schedules the job to run at 12:00 AM (midnight) every day.

Cron Syntax in Jenkins

The cron syntax used in Jenkins consists of 5 fields:

MINUTE HOUR DOM MONTH DOW

Where:

• MINUTE: 0 to 59

• HOUR: 0 to 23

• DOM (Day of Month): 1 to 31

• MONTH: 1 to 12 (or Jan, Feb, etc.)

• DOW (Day of Week): 0 to 7 (0 or 7 represents Sunday, 1 = Monday, and so on)

Examples of Jenkins Job Schedules

1. Run a job every 15 minutes

H/15 * * * *

Explanation: The job will run every 15 minutes, on any hour, day, and month.

2. Run a job daily at midnight

00***

Explanation: This job will run at 12:00 AM (midnight) every day.

3. Run a job at 6:00 AM every day

06***

Explanation: The job will run at 6:00 AM every day.

4. Run a job at 3:30 PM on weekdays (Monday to Friday)

30 15 * * 1-5

Explanation: The job will run at 3:30 PM from Monday to Friday.

18 | I n t e r v i e w Q u e s t i o n a n d A n s w e r p a r t 1
5. Run a job every Sunday at 1:00 PM

0 13 * * 0

Explanation: The job will run at 1:00 PM every Sunday (since 0 is Sunday).

6. Run a job at 8:00 AM on the 1st and 15th of every month

0 8 1,15 * *

Explanation: The job will run at 8:00 AM on the 1st and 15th day of every month.

7. Run a job at 11:00 PM on the last day of every month

0 23 L * *

Explanation: L stands for the last day of the month, so the job will run at 11:00 PM on the
last day of each month.

8. Run a job at 12:30 AM on the 1st Monday of every month

30 0 * * 1#1

Explanation: The job will run at 12:30 AM on the first Monday of every month.

9. Run a job every 5 hours

0 H/5 * * *

Explanation: The job will run every 5 hours starting from 12:00 AM.

10. Run a job every weekday at noon

0 12 * * 1-5

Explanation: The job will run at 12:00 PM (noon) from Monday to Friday.

Important Notes:

• H (Hash) Usage: Jenkins provides the H character to distribute load evenly. For
example, H 0 * * * would randomly choose a minute within the hour for the job to
start, helping to avoid congestion when multiple jobs are scheduled.

• Special Characters:

o L: Last day of the month or week.

o #: Used to specify the "nth" occurrence of a weekday in the month (e.g.,


1#1 means the first Monday of the month).

o ,: Separates multiple values (e.g., 1,15 for the 1st and 15th of the month).

o -: Defines ranges (e.g., 1-5 for Monday to Friday).

19 | I n t e r v i e w Q u e s t i o n a n d A n s w e r p a r t 1
Example: Schedule a Jenkins Job to Run at 10:00 PM Every Friday and 7:00 AM on
the 1st Day of Every Month

0 22 * * 5

071**

Explanation:

• The first line schedules the job to run at 10:00 PM every Friday.

• The second line schedules the job to run at 7:00 AM on the 1st day of every
month.

Example: Run a Job Every 30 Minutes on Weekdays (9:00 AM to 6:00 PM)

H/30 9-18 * * 1-5

Explanation: This job will run every 30 minutes from 9:00 AM to 6:00 PM, Monday to
Friday.

By using this cron syntax, you can efficiently manage your Jenkins jobs to execute at the
desired times!

43. Explain Agile methodology.

Agile methodology is an iterative and incremental approach to software development. It


focuses on delivering small, functional parts of the software in short cycles called
"sprints" (typically 2-4 weeks). Agile encourages collaboration between cross-functional
teams and stakeholders, adaptive planning, early delivery, continuous improvement,
and flexibility to change. It emphasizes user feedback and working software over
comprehensive documentation, which allows teams to respond quickly to market
demands or project changes.

44. How do you test a page?

To test a web page:

1. Functional Testing: Ensure that all buttons, forms, links, and interactive
elements function as expected.

2. UI Testing: Check the layout, responsiveness, alignment, and design across


browsers and devices.

20 | I n t e r v i e w Q u e s t i o n a n d A n s w e r p a r t 1
3. Cross-Browser Testing: Test the page in different browsers like Chrome, Firefox,
Edge, and Safari.

4. Performance Testing: Measure page load times, especially for critical sections.

5. Security Testing: Check for vulnerabilities like SQL injection, XSS, and CSRF.

6. API Testing: If the page interacts with backend services, test the API calls.

7. Automation: Automate repetitive tasks using tools like Selenium.

45. How do you start API testing?

API testing involves sending requests to the API endpoints and validating the responses.
Steps include:

1. Understand the API: Read API documentation to know the endpoints, methods
(GET, POST, PUT, DELETE), request parameters, headers, and authentication.

2. Create test cases: Write test cases for various scenarios, including positive,
negative, and edge cases.

3. Use tools: Start testing using tools like Postman or automate API tests using
tools like Rest Assured.

4. Validate responses: Check the status codes, response times, headers, and
data in the response body.

5. Check integration: Ensure that the API works well with other systems and
services.

46. What response codes do you know?

Some common HTTP response codes include:

• 200 OK: The request was successful.

• 201 Created: The request was successful, and a resource was created.

• 204 No Content: The request was successful, but there is no content to send in
the response.

• 400 Bad Request: The server could not understand the request due to invalid
syntax.

• 401 Unauthorized: Authentication is required, and the request lacks valid


credentials.

21 | I n t e r v i e w Q u e s t i o n a n d A n s w e r p a r t 1
• 403 Forbidden: The request was understood, but the server refuses to authorize
it.

• 404 Not Found: The requested resource could not be found.

• 500 Internal Server Error: The server encountered an error.

47. Can you explain the difference between 401 and 403 response codes?

• 401 Unauthorized: This means that authentication is required, but the client
either didn’t provide credentials or provided invalid credentials. The server
expects the client to authenticate first.

• 403 Forbidden: This means that the client is authenticated, but does not have
permission to access the resource. The server knows the user but refuses to
grant access.

48. How do you write a test case?

A test case consists of:

• Title: Descriptive title of what is being tested.

• Preconditions: Setup required before executing the test (e.g., user logged in).

• Test Steps: Detailed steps to execute the test.

• Expected Result: The expected outcome for each step.

• Actual Result: What actually happens after executing the test.

• Pass/Fail Criteria: Whether the test passed or failed based on expected results.

49. What parameters do you consider when creating test cases?

• Test case ID: Unique identifier.

• Test Description: Clear and concise description of the functionality being


tested.

• Preconditions: Any setup or configuration required before executing the test.

• Test Data: Input data necessary for the test.

• Test Steps: Step-by-step procedure to follow during the test.

• Expected Result: The anticipated outcome after executing the steps.

22 | I n t e r v i e w Q u e s t i o n a n d A n s w e r p a r t 1
• Priority: The importance of the test case.

• Dependencies: Any related tests or features.

• Postconditions: Any actions to clean up after the test.

50. How do you create a bug in Jira?

1. Click on "Create": In Jira, click the "Create" button to report a bug.

2. Select the project: Choose the relevant project.

3. Select the issue type: Set it to "Bug."

4. Enter the summary: Provide a concise description of the bug.

5. Description: Include detailed information about the bug, steps to reproduce,


expected vs. actual results, and any additional data like screenshots.

6. Set the priority: Assign the severity (Low, Medium, High, Critical).

7. Assign to: Assign the bug to the appropriate team member.

8. Labels/Components: Use labels or components for categorization.

9. Submit: Click “Create” to file the bug.

51. What is the difference between git push and git push --force?

• git push: Pushes your local commits to the remote repository. It will not override
changes if there is a conflict with the remote branch.

• git push --force: Force pushes your local commits, potentially overriding the
history in the remote repository. It is useful when you need to overwrite the
remote changes, but should be used with caution as it can cause data loss for
others who rely on the repository.

52. What do you know about git reset?

git reset is used to undo changes in the local repository. It can be used in different
modes:

• --soft: Moves the HEAD to a different commit, but keeps the changes in the
working directory and index (staging area).

23 | I n t e r v i e w Q u e s t i o n a n d A n s w e r p a r t 1
• --mixed: Moves the HEAD to a different commit, resets the index, but keeps the
changes in the working directory.

• --hard: Moves the HEAD to a different commit and discards all changes in the
working directory and index. This is the most destructive option, as it erases
uncommitted work.

53. How would you start with a BDD framework from scratch?

1. Set up the project: Use Maven or Gradle to manage dependencies.

2. Add dependencies: Include libraries like Cucumber, Gherkin, Selenium/Appium


(if necessary).

3. Define feature files: Write Gherkin scenarios in .feature files.

4. Create step definitions: Map Gherkin steps to actual code by writing step
definition classes.

5. Implement page objects: For UI tests, use the Page Object Model (POM) to
interact with the web/mobile elements.

6. Configure Cucumber runner: Use a test runner (like Cucumber TestNG) to


execute the scenarios.

7. Automate and validate: Run the tests and ensure the behavior matches the
expected outcomes.

54. What is the Cucumber framework?

Cucumber is a Behavior-Driven Development (BDD) framework that uses plain English


text (Gherkin) to define application behavior. It allows non-technical stakeholders to
understand how the application is expected to behave. Testers and developers map
Gherkin steps to code (step definitions) to automate the scenarios. Cucumber
integrates well with Java, Selenium, and other automation tools.

55. What is the purpose of pom.xml?

pom.xml (Project Object Model) is the configuration file for a Maven project. It manages
the project’s dependencies, build configuration, plugins, and versioning. Through the
pom.xml, developers can declare libraries and tools needed for the project, which are
automatically downloaded and added to the project classpath.

24 | I n t e r v i e w Q u e s t i o n a n d A n s w e r p a r t 1
56. Write a program to find duplicate values in a given map.

import java.util.*;

public class FindDuplicates {

public static void main(String[] args) {

Map<Integer, String> map = new HashMap<>();

map.put(1, "John");

map.put(2, "Doe");

map.put(3, "John");

map.put(4, "Jane");

Set<String> uniqueValues = new HashSet<>();

Set<String> duplicateValues = new HashSet<>();

for (String value : map.values()) {

if (!uniqueValues.add(value)) {

duplicateValues.add(value);

System.out.println("Duplicate values: " + duplicateValues);

57. Write a program to swap numbers without using a temporary variable.

public class SwapNumbers {

public static void main(String[] args) {

int a = 5;

25 | I n t e r v i e w Q u e s t i o n a n d A n s w e r p a r t 1
int b = 10;

System.out.println("Before swapping: a = " + a + ", b = " + b);

a = a + b; // a becomes 15

b = a - b; // b becomes 5

a = a - b; // a becomes 10

System.out.println("After swapping: a = " + a + ", b = " + b);

58. Write a program to reverse a list without using inbuilt methods.

import java.util.*;

public class ReverseList {

public static void main(String[] args) {

List<Integer> list = new ArrayList<>(Arrays.asList(1, 2, 3, 4, 5));

System.out.println("Original list: " + list);

for (int i = 0; i < list.size() / 2; i++) {

int temp = list.get(i);

list.set(i, list.get(list.size() - i - 1));

list.set(list.size() - i - 1, temp);

System.out.println("Reversed list: " + list);

26 | I n t e r v i e w Q u e s t i o n a n d A n s w e r p a r t 1
}

59. Write a program to determine if a number is odd or even using Python.

def check_odd_even(num):

if num % 2 == 0:

print(f"{num} is even")

else:

print(f"{num} is odd")

check_odd_even(7) # Example call

60. Locate an XPath for a given element.

To locate an element with XPath:

//input[@id='username']

//div[@class='container']/a

Example for finding a button using XPath:

//button[text()='Submit']

61. How do you handle frames in Selenium?

To handle frames in Selenium:

1. Switch to the frame: Use driver.switchTo().frame(index) or


driver.switchTo().frame("frameName").

2. Interact with elements: Once switched to the frame, you can locate elements
inside the frame.

3. Switch back to default: Use driver.switchTo().defaultContent() to exit the frame.

62. What waits are available in Selenium?

27 | I n t e r v i e w Q u e s t i o n a n d A n s w e r p a r t 1
• Implicit Wait: Waits for a certain amount of time before throwing an exception if
an element is not found. It applies globally.

driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);

• Explicit Wait: Waits until a certain condition is met for an element. It’s more
flexible and specific.

WebDriverWait wait = new WebDriverWait(driver, 20);

wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("element")));

• Fluent Wait: Waits for a condition while also defining the polling frequency and
ignoring exceptions.

Wait<WebDriver> wait = new FluentWait<>(driver)

.withTimeout(Duration.ofSeconds(30))

.pollingEvery(Duration.ofSeconds(5))

.ignoring(NoSuchElementException.class);

63. How do you handle alerts in Selenium?

To handle alerts in Selenium:

• Switch to alert: Use driver.switchTo().alert().

• Accept the alert: Use alert.accept().

• Dismiss the alert: Use alert.dismiss().

• Get alert text: Use alert.getText().

• Send input to alert: For prompt alerts, use alert.sendKeys("input").

☞ Can you explain the differences between Abstraction and Interfaces in Java?

1. Abstraction:

o Abstraction is a concept that focuses on hiding the implementation


details and showing only the essential features of an object.

o It can be achieved using abstract classes or interfaces.

28 | I n t e r v i e w Q u e s t i o n a n d A n s w e r p a r t 1
o An abstract class can have both abstract methods (without a body) and
concrete methods (with a body). It can also have instance variables and
constructors.

o Example:

abstract class Vehicle {

abstract void start();

void stop() {

System.out.println("Vehicle stopped.");

2. Interfaces:

o An interface is a reference type in Java that is similar to a class, but it can


contain only constants, method signatures, default methods, static
methods, and nested types.

o All methods in an interface are abstract by default (unless they are static
or default).

o A class can implement multiple interfaces, allowing for multiple


inheritance.

o Example:

interface Drivable {

void drive();

void park();

64. Write a program to determine whether the strings “Car” and “Arc” are anagrams
of each other.

import java.util.Arrays;

public class AnagramCheck {

public static void main(String[] args) {

String str1 = "Car";

29 | I n t e r v i e w Q u e s t i o n a n d A n s w e r p a r t 1
String str2 = "Arc";

// Remove spaces and convert to lower case

str1 = str1.replaceAll("\\s+", "").toLowerCase();

str2 = str2.replaceAll("\\s+", "").toLowerCase();

// Sort the characters of the strings

char[] charArray1 = str1.toCharArray();

char[] charArray2 = str2.toCharArray();

Arrays.sort(charArray1);

Arrays.sort(charArray2);

// Check if both sorted arrays are equal

boolean isAnagram = Arrays.equals(charArray1, charArray2);

System.out.println("Are the strings anagrams? " + isAnagram);

65. How can you perform a drag-and-drop action on an element in Selenium?

You can perform a drag-and-drop action using the Actions class in Selenium. Here's an
example:

import org.openqa.selenium.By;

import org.openqa.selenium.WebDriver;

import org.openqa.selenium.WebElement;

import org.openqa.selenium.interactions.Actions;

import org.openqa.selenium.chrome.ChromeDriver;

30 | I n t e r v i e w Q u e s t i o n a n d A n s w e r p a r t 1
public class DragAndDropExample {

public static void main(String[] args) {

WebDriver driver = new ChromeDriver();

driver.get("URL_OF_THE_PAGE");

WebElement sourceElement = driver.findElement(By.id("source"));

WebElement targetElement = driver.findElement(By.id("target"));

Actions actions = new Actions(driver);

actions.dragAndDrop(sourceElement, targetElement).perform();

driver.quit();

66. What are the differences between the get() and navigate().to() methods in
Selenium?

• get(String url):

o It is used to load a new web page in the current browser window.

o It waits for the page to load completely before proceeding.

o Example: driver.get("http://example.com");

• navigate().to(String url):

o It also loads a new web page in the current browser window.

o It can be used to navigate back and forth in the browser history.

o It is more flexible, allowing for actions like forward and back navigation.

o Example: driver.navigate().to("http://example.com");

67. How would you execute a context click and a double-click action in Selenium?

To execute a context click (right-click) and a double-click action, you can use the
Actions class as shown below:

31 | I n t e r v i e w Q u e s t i o n a n d A n s w e r p a r t 1
import org.openqa.selenium.By;

import org.openqa.selenium.WebDriver;

import org.openqa.selenium.WebElement;

import org.openqa.selenium.interactions.Actions;

import org.openqa.selenium.chrome.ChromeDriver;

public class ClickActions {

public static void main(String[] args) {

WebDriver driver = new ChromeDriver();

driver.get("URL_OF_THE_PAGE");

WebElement elementToRightClick = driver.findElement(By.id("rightClickElement"));

WebElement elementToDoubleClick =
driver.findElement(By.id("doubleClickElement"));

Actions actions = new Actions(driver);

// Right-click action

actions.contextClick(elementToRightClick).perform();

// Double-click action

actions.doubleClick(elementToDoubleClick).perform();

driver.quit();

68. What is the purpose of Selenium Grid, and how do you configure it?

Purpose:

32 | I n t e r v i e w Q u e s t i o n a n d A n s w e r p a r t 1
• Selenium Grid allows you to run tests on different machines against different
browsers in parallel. This speeds up the execution of tests and helps in cross-
browser testing.

Configuration:

1. Download Selenium Server: Download the Selenium Server jar file from the
Selenium website.

2. Start Hub: Open a command prompt and navigate to the directory where the
Selenium Server jar file is located. Start the hub with the following command:

java -jar selenium-server-standalone.jar -role hub

3. Start Node: On the node machine, open a command prompt and run:

bash

Copy code

java -jar selenium-server-standalone.jar -role node -hub http://<hub-


ip>:4444/grid/register

4. Configuration: You can configure nodes with desired capabilities (browsers,


versions, etc.) by modifying the node configuration JSON or using command-line
options.

69. How do you handle flaky tests in Selenium?

To handle flaky tests in Selenium:

1. Retries: Implement a retry mechanism for failed tests. You can use TestNG's
@RetryAnalyzer to automatically retry failed tests.

2. Synchronization: Ensure proper synchronization using explicit waits instead of


implicit waits to handle dynamic content loading.

3. Error Handling: Capture and analyze the errors to identify patterns and adjust
your test strategy accordingly.

4. Isolation: Run tests in isolation to avoid interference from other tests.

5. Environment Stability: Ensure that the testing environment is stable and


consistent.

☞ What is a Test Runner in TestNG, and what are its purposes?

A Test Runner in TestNG is a Java class that serves as an entry point for executing test
cases. Its purposes include:

• Executing Tests: It triggers the execution of test methods defined in test classes.
33 | I n t e r v i e w Q u e s t i o n a n d A n s w e r p a r t 1
• Test Configuration: It allows for configuration of test parameters and listeners.

• Reports: It generates test reports that provide insights into the execution results.

• Grouping: It enables the grouping of test cases for more organized execution.

Example of a simple Test Runner:

import org.testng.TestNG;

public class TestRunner {

public static void main(String[] args) {

TestNG testng = new TestNG();

testng.setTestClasses(new Class[] { YourTestClass.class });

testng.run();

70. What is the purpose of grouping tests in TestNG?

Grouping tests in TestNG allows you to categorize tests based on their functionality,
priority, or type. This helps in:

• Selective Execution: You can run specific groups of tests without executing the
entire test suite, which saves time.

• Organized Reporting: Grouping helps in generating organized reports, making it


easier to analyze results.

• Parameterized Testing: You can define different parameters for different groups,
facilitating varied test scenarios.

Example of grouping in testng.xml:

<suite name="SuiteName">

<test name="TestGroup1">

<groups>

<run>

<include name="group1"/>

</run>

34 | I n t e r v i e w Q u e s t i o n a n d A n s w e r p a r t 1
</groups>

<classes>

<class name="YourTestClass"/>

</classes>

</test>

</suite>

71. Can you explain the difference between rebase and merge in Git?

• Merge:

o Combines the changes from two branches and creates a new commit in
the current branch that contains both sets of changes.

o It preserves the history of both branches, showing a clear picture of what


happened and when.

• Rebase:

o Moves or combines a sequence of commits to a new base commit. It


effectively "rewrites" history.

o It results in a cleaner, linear project history but can lead to lost commit
history if not done carefully.

Use merge when you want to preserve the complete history, and use rebase for a
cleaner commit history.

72. What can you tell us about pipelines in CI/CD?

Pipelines in CI/CD (Continuous Integration/Continuous Deployment) are automated


workflows that enable software development teams to build, test, and deploy
applications more efficiently. Key aspects include:

• Automated Builds: Automatically build the code when changes are pushed to
the repository.

• Automated Testing: Run tests (unit, integration, UI) automatically after builds to
ensure code quality.

• Continuous Deployment: Automatically deploy code changes to production


environments after passing tests, ensuring rapid delivery of features and bug
fixes.

• Monitoring and Feedback: Provide feedback to developers on the success or


failure of builds and tests, facilitating quick resolutions.
35 | I n t e r v i e w Q u e s t i o n a n d A n s w e r p a r t 1
Common CI/CD tools include Jenkins, GitLab CI, CircleCI, and Travis CI.

Common Questions related to Domains

73. Can you describe your experience with the investment banking domain? What
challenges have you faced during the automation of banking features, and how did
you address them?

I have experience in the investment banking domain, particularly in automating testing


for various banking applications. Some challenges I faced include:

1. Complex Workflows: Investment banking applications often have complex


workflows with multiple dependencies. To address this, I implemented modular
test cases that could be reused across different scenarios.

2. Data Sensitivity: Handling sensitive financial data requires compliance with


regulations. I ensured that the test data was anonymized and used secure
environments for testing.

3. Integration with Legacy Systems: Many banking systems are built on legacy
technologies. I worked on creating wrappers and interfaces to integrate our
automated tests with these systems without disrupting their operations.

4. Performance Testing: High transaction volumes can affect performance. I


collaborated with the performance testing team to simulate load conditions and
ensure our automation scripts could handle peak loads.

74. What are three OOP concepts used in your framework? Please explain in detail.

1. Encapsulation:

o Encapsulation is the principle of bundling data (attributes) and methods


(functions) that operate on the data into a single unit or class. It restricts
direct access to some of the object's components, which is a means of
preventing unintended interference and misuse.

o Example: In my framework, I use encapsulation to keep the


implementation details of utility classes hidden and provide public
methods to perform actions. For instance, a class that manages
configurations might only expose methods to get or set configuration
values, while the internal representation remains private.

2. Inheritance:

36 | I n t e r v i e w Q u e s t i o n a n d A n s w e r p a r t 1
o Inheritance allows a new class (subclass or derived class) to inherit
properties and behaviors (methods) from an existing class (superclass or
base class). This promotes code reuse and establishes a hierarchical
relationship between classes.

o Example: In my test automation framework, I create a base class


BaseTest that contains common setup and teardown methods. Specific
test classes (e.g., LoginTest, PaymentTest) can then inherit from BaseTest,
reusing its functionality and allowing for more straightforward
maintenance.

3. Polymorphism:

o Polymorphism enables objects to be treated as instances of their parent


class, allowing for method overriding (same method name, different
implementation in subclasses) and method overloading (same method
name, different parameters).

o Example: In my framework, I might define a method executeTest() in a


base class Test and override it in subclasses for specific tests. This allows
me to call executeTest() on a Test reference, which will invoke the correct
implementation based on the actual object type.

75. What is the difference between ArrayList and LinkedList?

• ArrayList:

o Data Structure: Resizable array implementation.

o Performance: Fast random access (O(1)) due to contiguous memory


allocation, but slow for insertions and deletions (O(n)) as elements need
to be shifted.

o Use Case: Suitable for storing and accessing data frequently without
many modifications.

• LinkedList:

o Data Structure: Doubly linked list implementation.

o Performance: Slow random access (O(n)), but fast insertions and


deletions (O(1)) as they only involve changing references without shifting
elements.

o Use Case: Suitable for frequent modifications (insertion/deletion) of


elements.

76. How do POST and PUT methods differ in API testing?

37 | I n t e r v i e w Q u e s t i o n a n d A n s w e r p a r t 1
• POST:

o Used to submit data to the server to create a new resource.

o It typically results in a new resource being created, and the server


generates a unique identifier for it.

o Example: Submitting a new user registration.

• PUT:

o Used to update an existing resource on the server or create a resource if it


does not exist.

o It requires the client to send the entire resource representation, as it


replaces the existing resource with the new data.

o Example: Updating user details where the user ID is known.

77. Write a program to count and print the number of 'A's in a given string.

public class CountA {

public static void main(String[] args) {

String str = "Java is Amazing";

int count = 0;

for (char c : str.toCharArray()) {

if (c == 'A' || c == 'a') {

count++;

System.out.println("Number of 'A's: " + count);

78. What is a Stale Element Exception? Why does it occur, and how do you handle
it?

38 | I n t e r v i e w Q u e s t i o n a n d A n s w e r p a r t 1
• Definition: A Stale Element Exception occurs when the element you are trying to
interact with is no longer attached to the DOM (Document Object Model). This
typically happens when the page is refreshed, or the element is modified after it
has been located.

• Causes:

o The element has been removed or replaced in the DOM.

o The page has been navigated away from or reloaded.

• Handling:

o Re-fetch the element before performing actions on it.

o Use try-catch blocks to retry finding the element.

o Example:

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

try {

element.click();

} catch (StaleElementReferenceException e) {

element = driver.findElement(By.id("myElement")); // Re-fetch the element

element.click(); // Retry the action

79. Explain 401 and 500 error codes.

• 401 Unauthorized:

o This error indicates that the request has not been applied because it lacks
valid authentication credentials for the target resource.

o The client must authenticate itself to get the requested response.

• 500 Internal Server Error:

o This error indicates that the server encountered an unexpected condition


that prevented it from fulfilling the request.

o It is a generic error message and does not provide specific details about
the issue.

80. What is an Element Not Found Exception? Why does it occur, and how do you
handle it?

39 | I n t e r v i e w Q u e s t i o n a n d A n s w e r p a r t 1
• Definition: An Element Not Found Exception occurs when an attempt is made to
locate an element in the DOM, but the element cannot be found.

• Causes:

o The element may not be present in the current context (e.g., wrong page
or section).

o The element might not be rendered yet due to loading delays.

• Handling:

o Use explicit waits to wait for the element to become visible or present in
the DOM.

o Example:

WebDriverWait wait = new WebDriverWait(driver, 10);

WebElement element =
wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("myElement")));

81. Write a program to find the factorial of a number.

import java.util.Scanner;

public class Factorial {

public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);

System.out.print("Enter a number: ");

int num = scanner.nextInt();

long factorial = 1;

for (int i = 1; i <= num; i++) {

factorial *= i;

System.out.println("Factorial of " + num + " is: " + factorial);

scanner.close();

40 | I n t e r v i e w Q u e s t i o n a n d A n s w e r p a r t 1
}

82. Write a program to reverse a number.

import java.util.Scanner;

public class ReverseNumber {

public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);

System.out.print("Enter a number: ");

int num = scanner.nextInt();

int reversed = 0;

while (num != 0) {

int digit = num % 10;

reversed = reversed * 10 + digit;

num /= 10;

System.out.println("Reversed number is: " + reversed);

scanner.close();

83. What is the difference between List and Set in Java?

• List:

o Allows duplicate elements and maintains the order of insertion.

o Common implementations: ArrayList, LinkedList.

o Example:

List<String> list = new ArrayList<>();

41 | I n t e r v i e w Q u e s t i o n a n d A n s w e r p a r t 1
list.add("Apple");

list.add("Apple"); // Duplicates allowed

• Set:

o Does not allow duplicate elements and does not guarantee the order of
elements.

o Common implementations: HashSet, TreeSet.

o Example:

Set<String> set = new HashSet<>();

set.add("Apple");

set.add("Apple"); // Duplicates not allowed

84. Write a program to count duplicate characters in a string.

import java.util.HashMap;

public class DuplicateCharacterCount {

public static void main(String[] args) {

String str = "Java Programming";

HashMap<Character, Integer> charCountMap = new HashMap<>();

for (char c : str.toCharArray()) {

c = Character.toLowerCase(c); // To count duplicates case-insensitively

if (charCountMap.containsKey(c)) {

charCountMap.put(c, charCountMap.get(c) + 1);

} else {

charCountMap.put(c, 1);

System.out.println("Duplicate Characters:");

42 | I n t e r v i e w Q u e s t i o n a n d A n s w e r p a r t 1
for (HashMap.Entry<Character, Integer> entry : charCountMap.entrySet()) {

if (entry.getValue() > 1) {

System.out.println(entry.getKey() + ": " + entry.getValue());

85. Which CI/CD pipeline tools have you used? Can you explain your experience
with them?

I have used the following CI/CD pipeline tools:

• Jenkins: I have set up Jenkins for continuous integration and continuous


deployment. I configured jobs to build and test applications automatically upon
code commits and integrated it with version

86. Can you explain the differences between Abstraction and Interfaces in Java?

• Abstraction:

o Abstraction is the concept of hiding the complex implementation details


and showing only the essential features of an object. It allows you to
define a simplified model of a class and is achieved using abstract
classes and methods.

o Example: An abstract class Vehicle may have an abstract method move().


Different subclasses (like Car and Bike) would provide specific
implementations of move(), but the Vehicle class would not specify how
the vehicles move.

• Interfaces:

o An interface is a reference type in Java that can contain only constants,


method signatures, default methods, static methods, and nested types.
Interfaces provide a way to achieve abstraction and multiple inheritance.

o Example: An interface Animal might declare methods like eat() and


sleep(). Any class implementing Animal would have to provide concrete
implementations of these methods.

• Key Differences:

43 | I n t e r v i e w Q u e s t i o n a n d A n s w e r p a r t 1
o Implementation: Abstract classes can have both abstract methods
(without body) and concrete methods (with body), while interfaces can
only have abstract methods until Java 8 introduced default methods.

o Multiple Inheritance: A class can implement multiple interfaces but can


only inherit from one abstract class.

o Access Modifiers: Abstract classes can have access modifiers (public,


protected, etc.), whereas methods in interfaces are implicitly public.

87. Write a program to determine whether the strings “Car” and “Arc” are
anagrams of each other.

import java.util.Arrays;

public class AnagramCheck {

public static void main(String[] args) {

String str1 = "Car";

String str2 = "Arc";

// Convert both strings to lowercase and sort

char[] charArray1 = str1.toLowerCase().toCharArray();

char[] charArray2 = str2.toLowerCase().toCharArray();

Arrays.sort(charArray1);

Arrays.sort(charArray2);

// Check if sorted arrays are equal

if (Arrays.equals(charArray1, charArray2)) {

System.out.println(str1 + " and " + str2 + " are anagrams.");

} else {

System.out.println(str1 + " and " + str2 + " are not anagrams.");

44 | I n t e r v i e w Q u e s t i o n a n d A n s w e r p a r t 1
}

88. How can you perform a drag-and-drop action on an element in Selenium?

To perform a drag-and-drop action in Selenium, you can use the Actions class. Here's
an example:

import org.openqa.selenium.By;

import org.openqa.selenium.WebDriver;

import org.openqa.selenium.WebElement;

import org.openqa.selenium.chrome.ChromeDriver;

import org.openqa.selenium.interactions.Actions;

public class DragAndDropExample {

public static void main(String[] args) {

WebDriver driver = new ChromeDriver();

driver.get("URL_OF_YOUR_PAGE");

// Locate the source and target elements

WebElement source = driver.findElement(By.id("sourceElementId"));

WebElement target = driver.findElement(By.id("targetElementId"));

// Create an Actions object

Actions actions = new Actions(driver);

actions.dragAndDrop(source, target).perform();

driver.quit();

45 | I n t e r v i e w Q u e s t i o n a n d A n s w e r p a r t 1
89. What are the differences between the get() and navigate().to() methods in
Selenium?

• get():

o The get() method is used to open a specific URL in the browser. It waits for
the page to load completely before returning control to the script.

o Example: driver.get("http://www.example.com");

• navigate().to():

o The navigate().to() method is also used to open a specific URL, but it is


part of the Navigation interface. It allows you to navigate to URLs while
providing additional navigation features like back, forward, and refresh.

o It may not wait for the page to load completely, depending on how it is
implemented.

o Example: driver.navigate().to("http://www.example.com");

90. How would you execute a context click and a double-click action in Selenium?

To perform a context click (right-click) and a double-click action in Selenium, you can
also use the Actions class.

Context Click Example:

import org.openqa.selenium.By;

import org.openqa.selenium.WebDriver;

import org.openqa.selenium.WebElement;

import org.openqa.selenium.chrome.ChromeDriver;

import org.openqa.selenium.interactions.Actions;

public class ContextClickExample {

public static void main(String[] args) {

WebDriver driver = new ChromeDriver();

driver.get("URL_OF_YOUR_PAGE");

// Locate the element to right-click

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

46 | I n t e r v i e w Q u e s t i o n a n d A n s w e r p a r t 1
// Create an Actions object and perform context click

Actions actions = new Actions(driver);

actions.contextClick(element).perform();

driver.quit();

Double Click Example:

import org.openqa.selenium.By;

import org.openqa.selenium.WebDriver;

import org.openqa.selenium.WebElement;

import org.openqa.selenium.chrome.ChromeDriver;

import org.openqa.selenium.interactions.Actions;

public class DoubleClickExample {

public static void main(String[] args) {

WebDriver driver = new ChromeDriver();

driver.get("URL_OF_YOUR_PAGE");

// Locate the element to double-click

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

// Create an Actions object and perform double click

Actions actions = new Actions(driver);

actions.doubleClick(element).perform();

driver.quit();

47 | I n t e r v i e w Q u e s t i o n a n d A n s w e r p a r t 1
}

91. What is the purpose of Selenium Grid, and how do you configure it?

• Purpose of Selenium Grid:

o Selenium Grid allows you to run your tests on multiple machines and
browsers simultaneously, facilitating parallel test execution. It is useful
for reducing test execution time and for testing across different
environments.

• Configuration:

1. Set up a Hub:

▪ Start the Selenium server as a hub using the command:

java -jar selenium-server-standalone.jar -role hub

2. Set up Nodes:

▪ Start nodes on different machines or on the same machine with a


different command, pointing to the hub:

java -jar selenium-server-standalone.jar -role node -hub


http://localhost:4444/grid/register

3. Run Tests:

▪ In your test scripts, you can specify the hub URL to direct tests to
run on the grid.

92. How do you handle flaky tests in Selenium?

Flaky tests are tests that sometimes pass and sometimes fail without any changes in
the code. Here are some

93. What are three OOP concepts used in your framework? Please explain in detail.

The three main OOP (Object-Oriented Programming) concepts I use in my framework


are:

• Encapsulation: This involves bundling the data (attributes) and methods


(functions) that operate on the data into a single unit, or class. It helps to restrict
direct access to some of an object's components, which is a means of
preventing unintended interference and misuse of the methods and data. For
example, I create classes for different components in my automation framework,
48 | I n t e r v i e w Q u e s t i o n a n d A n s w e r p a r t 1
such as AppiumService, that encapsulate the necessary methods for initializing
and managing Appium sessions.

• Inheritance: This allows a new class (subclass) to inherit properties and


behavior (methods) from an existing class (superclass). This promotes code
reusability and establishes a natural hierarchy between classes. In my
framework, I use inheritance to create specialized classes that extend base
classes. For example, I might have a base class BaseTest and subclasses like
MobileTest and WebTest that inherit common functionalities while implementing
specific behaviors.

• Polymorphism: This concept allows methods to do different things based on the


object it is acting upon, even if they share the same name. There are two types:
compile-time (method overloading) and runtime (method overriding). In my
framework, I implement polymorphism by allowing different types of tests (unit,
integration, etc.) to execute a common runTest() method, which behaves
differently based on the context of the test.

94. What is the difference between ArrayList and LinkedList?

• ArrayList:

o It is implemented using a dynamic array that can grow as needed.


ArrayLists allow fast random access to elements due to their array-based
structure but can be slow for insertions and deletions, particularly in the
middle of the list because elements must be shifted.

o Use case: Best when you need to frequently access elements by index or
when the size of the list remains relatively stable.

• LinkedList:

o It is implemented as a doubly linked list, where each element (node)


contains a reference to both the previous and next node. LinkedLists
allow for efficient insertions and deletions because you only need to
change the references, but accessing an element by index is slower since
it requires traversal from the beginning or end of the list.

o Use case: Best when you expect to make a lot of insertions and deletions,
especially in the middle of the list.

95. How do POST and PUT methods differ in API testing?

• POST:

49 | I n t e r v i e w Q u e s t i o n a n d A n s w e r p a r t 1
o The POST method is used to send data to the server to create a new
resource. It is not idempotent, meaning multiple identical requests can
result in different effects (e.g., creating multiple entries).

o Example: Sending a JSON payload to create a new user in a database.

• PUT:

o The PUT method is used to update an existing resource or create a new


resource if it does not exist. It is idempotent, meaning multiple identical
requests will have the same effect as a single request.

o Example: Sending a JSON payload to update an existing user's details.

96. Write a program to count and print the number of 'A's in a given string.

public class CountA {

public static void main(String[] args) {

String input = "Aardvark";

int count = 0;

for (char c : input.toCharArray()) {

if (c == 'A' || c == 'a') {

count++;

System.out.println("Number of 'A's: " + count);

97. What is a Stale Element Exception? Why does it occur, and how do you handle
it?

• A Stale Element Exception occurs in Selenium when a WebElement reference


becomes invalid, typically because the DOM has changed since the element was
located. This can happen if the page is refreshed, navigated away from, or if the
element has been removed or replaced in the DOM.

50 | I n t e r v i e w Q u e s t i o n a n d A n s w e r p a r t 1
• Handling it:

o Re-locate the element just before performing the action.

o Use try-catch blocks to handle the exception and retry locating the
element.

try {

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

// Perform actions with the element

} catch (StaleElementReferenceException e) {

WebElement element = driver.findElement(By.id("elementId")); // Re-locate the


element

98. Explain 401 and 500 error codes.

• 401 Unauthorized:

o This error code indicates that the request requires user authentication. It
means the client has not provided valid authentication credentials for the
target resource. To resolve this, the client must authenticate itself with the
correct credentials.

• 500 Internal Server Error:

o This is a generic error message indicating that the server encountered an


unexpected condition that prevented it from fulfilling the request. It
usually signifies a problem on the server side rather than with the client's
request. Troubleshooting requires checking the server logs to identify the
issue.

99. What is an Element Not Found Exception? Why does it occur, and how do you
handle it?

• An Element Not Found Exception occurs in Selenium when an attempt is made


to locate an element that is not present in the DOM at the time of the request.
This can happen for various reasons, such as timing issues, changes in the page
structure, or incorrect locators.

• Handling it:

o Ensure that the locator used is correct.

51 | I n t e r v i e w Q u e s t i o n a n d A n s w e r p a r t 1
o Use explicit waits to allow the element to become present before trying to
interact with it.

WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));

WebElement element =
wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("elementId")));

100. Write a program to find the factorial of a number.

public class Factorial {

public static void main(String[] args) {

int number = 5; // Change this number to calculate its factorial

int result = 1;

for (int i = 1; i <= number; i++) {

result *= i;

System.out.println("Factorial of " + number + " is " + result);

101. Write a program to reverse a number.

public class ReverseNumber {

public static void main(String[] args) {

int number = 12345; // Change this number to reverse

int reversed = 0;

while (number != 0) {

int digit = number % 10;

reversed = reversed * 10 + digit;

number /= 10;

}
52 | I n t e r v i e w Q u e s t i o n a n d A n s w e r p a r t 1
System.out.println("Reversed number is " + reversed);

102. What is the difference between List and Set in Java?

• List:

o A List is an ordered collection that allows duplicate elements. It


maintains the insertion order, meaning you can access elements by their
index.

o Common implementations include ArrayList, LinkedList, and Vector.

• Set:

o A Set is an unordered collection that does not allow duplicate elements. It


does not guarantee the order of elements.

o Common implementations include HashSet, LinkedHashSet, and


TreeSet.

103. Write a program to count duplicate characters in a string.

import java.util.HashMap;

public class CountDuplicateChars {

public static void main(String[] args) {

String input = "hello world";

HashMap<Character, Integer> charCount = new HashMap<>();

for (char c : input.toCharArray()) {

charCount.put(c, charCount.getOrDefault(c, 0) + 1);

System.out.println("Duplicate characters:");

for (char c : charCount.keySet()) {

53 | I n t e r v i e w Q u e s t i o n a n d A n s w e r p a r t 1
if (charCount.get(c) > 1) {

System.out.println(c + ": " + charCount.get(c) + " times");

104. Which CI/CD pipeline tools have you used? Can you explain your experience
with them?

I have worked with several CI/CD pipeline tools, including:

• Jenkins: I have set up Jenkins for automating builds and tests. I configured jobs
for various projects, integrating with Git for version control. I also implemented
plugins for notifications and reporting.

• GitLab CI: I utilized GitLab CI for CI/CD in projects hosted on GitLab. I wrote
.gitlab-ci.yml files to define stages for building, testing, and deploying
applications.

• CircleCI: I used CircleCI to automate testing and deployment processes,


creating workflows for parallel testing and deployment to various environments.

105. What domain experience do you have in your career so far?

I have primarily worked in the investment banking domain, focusing on automating


testing for financial applications. My experience includes testing transaction processing
systems, account management features, and compliance-related functionalities,
collaborating closely with stakeholders to ensure quality and adherence to regulatory
standards.

106. How many team members have you led in your projects?

I have led teams of varying sizes, ranging from 5 to 10 members. My leadership


experience includes mentoring junior team members, coordinating project tasks, and
facilitating communication between cross-functional teams to ensure successful
project delivery.

107. Can you explain Polymorphism, along with examples of Method Overloading
and Method Overriding?

• Polymorphism:

54 | I n t e r v i e w Q u e s t i o n a n d A n s w e r p a r t 1
o Polymorphism allows objects of different classes to be treated as objects
of a common superclass. It enables a single action to behave differently
based on the context.

• Method Overloading:

o Method overloading occurs when two or more methods in the same class
have the same name but different parameters (different type or number).
It is resolved at compile-time.

public class MathUtils {

public int add(int a, int b) {

return a + b;

public double add(double a, double b) {

return a + b;

public int add(int a, int b, int c) {

return a + b + c;

• Method Overriding:

o Method overriding occurs when a subclass provides a specific


implementation of a method that is already defined in its superclass. It is
resolved at runtime.

class Animal {

void sound() {

System.out.println("Animal makes a sound");

55 | I n t e r v i e w Q u e s t i o n a n d A n s w e r p a r t 1
class Dog extends Animal {

void sound() {

System.out.println("Dog barks");

public class TestPolymorphism {

public static void main(String[] args) {

Animal myDog = new Dog();

myDog.sound(); // Output: Dog barks

108. Rate yourself out of 5 in Java, Selenium, and Cucumber.

• Java: 4/5 - I have strong knowledge and experience in Java, including OOP
concepts, data structures, and design patterns.

• Selenium: 4/5 - I am proficient in Selenium for web automation and have


implemented various testing frameworks and practices using it.

• Cucumber: 3.5/5 - I have experience with Cucumber for BDD (Behavior-Driven


Development) testing and can effectively write feature files and step definitions.

104. What are your roles and responsibilities in your current/previous role?

In my current role as a Software Lead, my responsibilities include:

• Leading a team of testers to design and implement automated testing


frameworks for mobile and web applications.

• Collaborating with development teams to integrate testing into the CI/CD


pipeline.

• Writing and executing test plans and test cases to ensure application quality.

• Conducting code reviews and mentoring junior team members.

56 | I n t e r v i e w Q u e s t i o n a n d A n s w e r p a r t 1
• Analyzing test results, identifying issues, and collaborating with developers for
resolution.

105. Can you explain the framework you've worked with?

I have worked with several automation frameworks, including:

• Data-Driven Framework: This framework reads test data from external sources
like Excel or CSV files and runs the same test with different data inputs.

• Keyword-Driven Framework: This uses keywords to represent actions in tests. I


define keywords in a properties file and map them to the corresponding code
implementation.

• Behavior-Driven Development (BDD): I have used Cucumber to write feature


files and step definitions for BDD testing, enabling collaboration between
technical and non-technical stakeholders.

106. Explain the different ways to handle dropdowns in Selenium.

There are several ways to handle dropdowns in Selenium:

• Using Select class: For standard <select> dropdowns, you can use the Select
class to select options by visible text, value, or index.

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

dropdown.selectByVisibleText("Option 1");

• Using WebElement: For non-standard dropdowns, you can click the dropdown
and select options based on their XPath or CSS selectors.

driver.findElement(By.id("dropdownId")).click(); // Open dropdown

driver.findElement(By.xpath("//li[text()='Option 1']")).click(); // Select option

107. Give a scenario where you need to click on Electronics in Flipkart using the
Action class.

In this scenario, we might need to use the Action class to move to a menu item that may
not be directly clickable or requires hover action before selection. Here's how you can
do it:

Actions actions = new Actions(driver);

WebElement electronicsMenu =
driver.findElement(By.xpath("//span[text()='Electronics']"));

actions.moveToElement(electronicsMenu).click().perform();

108. What is Polymorphism in Java?

57 | I n t e r v i e w Q u e s t i o n a n d A n s w e r p a r t 1
Polymorphism in Java is the ability of a method to perform different tasks based on the
object that it is acting upon. It allows for methods to have the same name but behave
differently in different contexts. There are two types of polymorphism:

• Compile-time polymorphism (Method Overloading): Same method name with


different parameters.

• Runtime polymorphism (Method Overriding): A subclass provides a specific


implementation of a method that is already defined in its superclass.

109. What is an interface in Java?

An interface in Java is a reference type that can contain only constants, method
signatures, default methods, static methods, and nested types. It cannot contain
instance fields or constructors. Interfaces are used to specify what a class must do,
without dictating how it must do it. They provide a way to achieve abstraction and
multiple inheritance.

Example:

interface Animal {

void sound(); // method signature

class Dog implements Animal {

public void sound() {

System.out.println("Dog barks");

110. What is Cucumber, and how does it fit in your testing strategy?

Cucumber is a BDD testing framework that allows writing test cases in a natural
language format (Gherkin) that can be understood by non-technical stakeholders. It fits
into my testing strategy by facilitating collaboration between developers, testers, and
business analysts. By defining acceptance criteria in Gherkin syntax, I ensure that the
tests are closely aligned with business requirements.

111. What is the difference between Scenario Outline and Data Tables in
Cucumber?

58 | I n t e r v i e w Q u e s t i o n a n d A n s w e r p a r t 1
• Scenario Outline: It allows for running the same scenario multiple times with
different sets of inputs. It uses placeholders and an example table to define the
variable data.

Example:

Scenario Outline: Login with different credentials

Given I navigate to the login page

When I enter "<username>" and "<password>"

Then I should see the "<message>"

Examples:

| username | password | message |

| user1 | pass1 | Successful Login |

| user2 | pass2 | Invalid Credentials|

• Data Tables: They allow for passing a list of values or a structured set of data
within a single step. It is used for scenarios that require multiple inputs in a
tabular format.

Example:

Given the following users:

| username | password |

| user1 | pass1 |

| user2 | pass2 |

112. Explain what Hooks are in Cucumber.

Hooks in Cucumber are blocks of code that run at specific points in the test execution
lifecycle. They allow for setting up or tearing down tests, managing preconditions, or
logging test execution. Common hooks include @Before, @After, @BeforeStep, and
@AfterStep.

Example:

@Before

public void setUp() {

// Code to set up test environment

59 | I n t e r v i e w Q u e s t i o n a n d A n s w e r p a r t 1
}

@After

public void tearDown() {

// Code to clean up after tests

113. What is Tagging in Cucumber, and how is it useful?

Tagging in Cucumber allows you to categorize and filter scenarios based on tags. It
helps in executing a subset of tests or organizing tests based on specific features or
requirements. You can use tags in the command line to run specific scenarios or in the
feature files to group related tests.

Example:

@smoke

Scenario: Verify login functionality

You can run tests with the @smoke tag using the command:

cucumber --tags @smoke

114. What is the difference between Dry Run and Strict in Cucumber?

• Dry Run: This feature checks if all steps in the feature file have corresponding
step definitions. It does not execute the tests but verifies the mapping between
the feature file and step definitions.

• Strict: When set to strict mode, Cucumber will fail the execution if there are any
undefined or pending steps in the feature file. It ensures that all steps have
corresponding implementations before executing the tests.

115. Does Cucumber support TestNG?

Yes, Cucumber supports TestNG integration. You can run Cucumber tests using TestNG
by creating a TestNG runner class and using the @CucumberOptions annotation to
specify the feature files and step definitions.

Example:

@RunWith(Cucumber.class)

@CucumberOptions(features = "src/test/resources/features", glue = "stepDefinitions")

public class TestRunner {

60 | I n t e r v i e w Q u e s t i o n a n d A n s w e r p a r t 1
}

116. What is encapsulation? Provide an example with code.

Encapsulation is an OOP principle that involves bundling the data (attributes) and
methods (functions) that operate on the data into a single unit, typically a class, while
restricting access to some of the object's components. This is achieved through access
modifiers (private, protected, public).

Example:

public class BankAccount {

private double balance; // Private variable

public void deposit(double amount) { // Public method

balance += amount;

public double getBalance() { // Public method

return balance;

117. Write a Java program to find duplicate characters from a word without using
for loops.

import java.util.HashMap;

public class DuplicateCharacters {

public static void main(String[] args) {

String word = "programming";

HashMap<Character, Integer> charCount = new HashMap<>();

word.chars().mapToObj(c -> (char) c).forEach(c ->

charCount.put(c, charCount.getOrDefault(c, 0) + 1)

61 | I n t e r v i e w Q u e s t i o n a n d A n s w e r p a r t 1
);

charCount.forEach((k, v) -> {

if (v > 1) {

System.out.println(k + ": " + v + " times");

});

118. Explain the use of an object repository in Selenium (.properties file).

An object repository in Selenium is a centralized location for storing web element


locators. It can be implemented using a .properties file that maps logical names to the
actual locators (XPath, CSS selectors, etc.). This approach enhances maintainability, as
changes to locators need to be made only in the repository file rather than throughout
the code.

Example:

# ObjectRepository.properties

loginButton = //button[@id='login']

usernameField = //input[@name='username']

passwordField = //input[@name='password']

119. How do you store data in a .properties file?

You can store data in a .properties file by using key-value pairs. Each line represents a
key-value mapping, with the key on the left and the value on the right, separated by an
equal sign (=).

Example:

baseUrl = https://example.com

timeout = 30

browser = chrome

19) What is Page Factory in Selenium?

62 | I n t e r v i e w Q u e s t i o n a n d A n s w e r p a r t 1
Page Factory is a design pattern in Selenium that provides an efficient way to initialize
Page Objects. It uses annotations to define the web elements in the Page Object class
and initializes them lazily, meaning elements are only found when they are accessed for
the first time.

Example:

import org.openqa.selenium.WebElement;

import org.openqa.selenium.support.FindBy;

import org.openqa.selenium.support.PageFactory;

public class LoginPage {

@FindBy(id = "username")

private WebElement usernameField;

@FindBy(id = "password")

private WebElement passwordField;

public LoginPage(WebDriver driver) {

PageFactory.initElements(driver, this);

public void login(String username, String password) {

usernameField.sendKeys(username);

passwordField.sendKeys(password);

// submit login form

120. What is the difference between @BeforeClass and @BeforeTest in TestNG?

63 | I n t e r v i e w Q u e s t i o n a n d A n s w e r p a r t 1
• @BeforeClass: This annotation runs once before any of the test methods in the
current class. It is typically used for setup that is class-specific, such as
initializing WebDriver for tests in that class.

• @BeforeTest: This annotation runs once before any test methods belonging to
the classes that are part of the test tag in the TestNG XML file. It is used for test
setup that needs to be shared across multiple classes or test methods.

121. What are the tasks typically written under the @BeforeTest annotation?

Tasks typically written under the @BeforeTest annotation may include:

• Setting up the test environment.

• Initializing common resources, such as WebDriver or database connections.

• Configuring external libraries or services required for the tests.

122. How can you skip a test case in Cucumber?

You can skip a test case in Cucumber by using the @skip tag. When running the tests,
you can exclude tests with this tag.

Example:

@skip

Scenario: This scenario is skipped

Given I am on the login page

When I enter valid credentials

Then I should be logged in

You can run tests excluding this tag using:

cucumber --tags ~@skip

123. How do you rerun failed test cases in TestNG?

To rerun failed test cases in TestNG, you can use the ITestListener interface and
implement the onTestFailure method to rerun failed tests. Alternatively, you can
configure the testng.xml file to specify the rerun-failed configuration.

Example:

<listeners>

<listener class-name="org.testng.IRetryAnalyzer"/>

</listeners>

64 | I n t e r v i e w Q u e s t i o n a n d A n s w e r p a r t 1
124. How do you group and run test cases in TestNG?

You can group test cases in TestNG using the groups attribute in the @Test annotation
and by specifying the groups in the testng.xml file.

Example:

@Test(groups = {"smoke"})

public void testLogin() {

// test code

In testng.xml:

<suite name="Suite">

<test name="SmokeTests">

<groups>

<run>

<include name="smoke"/>

</run>

</groups>

<classes>

<class name="TestClass"/>

</classes>

</test>

</suite>

125. What would you include under the @BeforeSuite annotation?

Under the @BeforeSuite annotation, you can include tasks that need to be executed
once before all tests in the suite, such as:

• Setting up the environment.

• Configuring reports or logging.

• Initializing databases or services required for the tests.

126. Can you explain the different locators used in Selenium?

Selenium provides several types of locators to identify web elements:


65 | I n t e r v i e w Q u e s t i o n a n d A n s w e r p a r t 1
• ID: Locate elements by their unique ID attribute. Example:
driver.findElement(By.id("elementId")).

• Name: Locate elements by their name attribute. Example:


driver.findElement(By.name("elementName")).

• Class Name: Locate elements by their class attribute. Example:


driver.findElement(By.className("className")).

• Tag Name: Locate elements by their HTML tag name. Example:


driver.findElement(By.tagName("input")).

• Link Text: Locate anchor tags (<a>) by the text they display. Example:
driver.findElement(By.linkText("Click here")).

• Partial Link Text: Locate anchor tags by a part of their text. Example:
driver.findElement(By.partialLinkText("Click")).

• CSS Selector: Locate elements using CSS selectors. Example:


driver.findElement(By.cssSelector(".class #id")).

• XPath: Locate elements using XPath expressions. Example:


driver.findElement(By.xpath("//div[@id='id']")).

127. What is a collection in Java?

A collection in Java is a data structure that allows you to store and manipulate groups of
related objects. Java Collections Framework provides various interfaces and classes,
such as List, Set, Map, and their implementations (ArrayList, HashSet, HashMap, etc.).
Collections provide methods for storing, accessing, and manipulating data efficiently.

28) Explain the hierarchy of exceptions in Java.

Java exceptions are divided into two main categories:

• Checked Exceptions: These are exceptions that are checked at compile-time.


The code must handle these exceptions using try-catch blocks or declare them
using the throws keyword. Examples include IOException, SQLException.

• Unchecked Exceptions: These are exceptions that are not checked at compile-
time and include runtime exceptions. They extend RuntimeException and do not
require explicit handling. Examples include NullPointerException,
ArrayIndexOutOfBoundsException.

The hierarchy can be summarized as follows:

• Throwable

o Error (not meant to be caught)

66 | I n t e r v i e w Q u e s t i o n a n d A n s w e r p a r t 1
o Exception

▪ Checked Exceptions

▪ Unchecked Exceptions

▪ RuntimeException

67 | I n t e r v i e w Q u e s t i o n a n d A n s w e r p a r t 1

You might also like