0% found this document useful (0 votes)
2 views28 pages

Interview Questions - Selenium With Java

The document provides a comprehensive overview of various topics related to Selenium automation, including WebDriverManager, wait strategies (Implicit, Explicit, Fluent), XPath syntax, report generation in Maven, Cucumber features, Jenkins job scheduling, and differences between Java collections. It also covers key programming concepts such as arrays vs. linked lists, binary search, palindrome checking, HTTP status codes, and the distinctions between POST and PUT methods in API usage. Overall, it serves as a guide for understanding automation testing and programming best practices.

Uploaded by

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

Interview Questions - Selenium With Java

The document provides a comprehensive overview of various topics related to Selenium automation, including WebDriverManager, wait strategies (Implicit, Explicit, Fluent), XPath syntax, report generation in Maven, Cucumber features, Jenkins job scheduling, and differences between Java collections. It also covers key programming concepts such as arrays vs. linked lists, binary search, palindrome checking, HTTP status codes, and the distinctions between POST and PUT methods in API usage. Overall, it serves as a guide for understanding automation testing and programming best practices.

Uploaded by

ankitkumar5
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Interview Questions

1. What is WebDriverManager, and how does it assist in Selenium automation?


WebDriverManager is a Java library developed by Boni García that automates the
management of browser drivers (like ChromeDriver, GeckoDriver, etc.) required for
Selenium WebDriver.

Problem without WebDriverManager:

Traditionally, to use Selenium WebDriver, you had to:

 Download the browser driver manually (e.g., [Link]).


 Ensure the driver version matches the browser version.
 Set the system property using:

[Link]("[Link]",
"path/to/chromedriver");

This process is manual, error-prone, and not scalable in CI/CD environments.

How WebDriverManager helps:

WebDriverManager automates this entire process.

✅ Benefits:

 Automatically downloads the correct version of the driver.


 No need to set the path manually.
 Keeps the drivers up-to-date.
 Works across platforms (Windows, macOS, Linux).
 Great for CI/CD pipelines (no manual setup).

2. What are the differences between Implicit Wait, Explicit Wait, and Fluent Wait in
Selenium?

1. Implicit Wait

🔹 Definition: Tells WebDriver to poll the DOM for a certain amount of time when trying to
find an element if it’s not immediately available.

🔹 Applies to: All elements globally (applies throughout the WebDriver session).

🔹 Syntax:

[Link]().timeouts().implicitlyWait([Link](1
0));
Key Points:

 Set once, applies to all findElement/findElements.


 Not customizable per element.
 Can slow down execution if used with explicit wait together.

2. Explicit Wait

🔹 Definition: Waits for a certain expected condition to occur before proceeding.

🔹 Applies to: Specific element(s).

🔹 Syntax:

WebDriverWait wait = new WebDriverWait(driver,


[Link](10));
[Link]([Link]([Link]
("elementId")));

🔹 Key Points:

 More flexible and customizable than implicit wait.


 Waits for specific conditions (visibility, clickable, presence, etc.).
 Used when element takes time to appear/change.

3. Fluent Wait

🔹 Definition: A more advanced version of explicit wait. It defines:

 Timeout
 Polling frequency
 Exceptions to ignore

🔹 Syntax:

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


.withTimeout([Link](20))
.pollingEvery([Link](2))
.ignoring([Link]);

WebElement element = [Link](driver ->


[Link]([Link]("elementId")));

🔹 Key Points:

 Useful when elements load at different speeds.


 Can be tuned with polling time.
 Can ignore exceptions during polling (e.g., NoSuchElementException).
3. What is the XPath syntax to select the following siblings?
In XPath, to select the following siblings of a node (i.e., elements that share the same
parent and come after the current element in the DOM), we use:
//tagname[@attribute='value']/following-sibling::tagname
//tr[@id='row1']/following-sibling::tr[1]
//li[1]/following-sibling::li
//div[text()='First']/following-sibling::div[text()='Third']
4. How can reports be generated using Maven in Selenium projects?

In Selenium Maven projects, reports can be generated automatically using Maven plugins
like:

1. Surefire Plugin + TestNG/JUnit Reports

When using TestNG or JUnit, Maven’s Surefire Plugin generates basic HTML/XML
reports by default.

📦 Add to [Link]:

2. Using TestNG + ReportNG (Advanced HTML reports)

ReportNG is an older but prettier HTML reporting plugin used with TestNG.

⚠️ReportNG is no longer maintained. Use ExtentReports or Allure instead for modern


projects.

3. Using ExtentReports (Recommended for Rich HTML Reports)

ExtentReports is a powerful library to generate custom HTML reports with:

 Screenshots
 Logs
 Pass/Fail Summary

📦 Add to [Link]:

4. Allure Reports (For professional CI/CD reporting)

Allure is a modern report framework supporting attachments, graphs, and history.

📦 Add Allure Maven Plugin:


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

Both Scenario Outline and Data Tables in Cucumber are used for data-driven testing, but
they serve different purposes and are used in different ways.

🔸 1. Scenario Outline

Used to run the same scenario multiple times with different sets of input data.

🔹 Syntax:
Scenario Outline: Login with valid credentials
Given user is on login page
When user enters "<username>" and "<password>"
Then login should be successful

Examples:
| username | password |
| user1 | pass1 |
| user2 | pass2 |

✅ Key Features:

 Placeholders in angle brackets: <username>, <password>.


 Examples table provides the test data.
 Each row creates a new scenario instance.

🔸 2. Data Tables

Used to pass a set of values to a step as a list or map (e.g., filling form fields, verifying table
data).

🔹 Syntax:
Scenario: Fill user details form
Given the user enters the following information:
| name | John |
| email | john@[Link] |
| country | India |

✅ Key Features:
 Used inside a single step, not for multiple iterations.
 Parsed in step definition using DataTable object in Java.

@Given("the user enters the following information:")


public void enterUserInfo(DataTable dataTable) {
Map<String, String> userInfo = [Link]();
[Link]([Link]("name"));
}

🔁 Tabular Comparison:
Feature Scenario Outline Data Table

Use Case Multiple iterations of a scenario Pass structured data to a step

Syntax <placeholder> + Examples Table under a step

Executes Multiple Times ✅ Yes ❌ No (single scenario)

Data Format Table of inputs per row Key-value pairs or 2D table

Typical Usage Login with different users Form filling, table validation

🔚 Summary:

 Use Scenario Outline when you want to repeat a scenario for multiple sets of data.
 Use Data Tables when you want to pass complex or structured data to a single
step.

6. If multiple feature files contain the same set of steps, such as Login and Logout, how
can this repetition be avoided in a Cucumber feature file?

In Cucumber, when multiple feature files contain the same set of steps (like Login and
Logout), you can avoid repetition by reusing step definitions and structuring your
features smartly. Here's how you can handle it:

✅ 1. Reusing Step Definitions

You don’t need to duplicate step definitions across feature files. If a step is defined once in
your step definition classes, it can be used in any number of feature files.

Example:
# [Link]
Scenario: User logs in successfully
Given User is on login page
When User enters valid credentials
Then User is navigated to the dashboard

# [Link]
Scenario: User logs out
Given User is logged in
When User clicks logout button
Then User is redirected to login page

You can have these steps implemented only once in the Java StepDefinitions class,
and use them across feature files.

✅ 2. Background Keyword

Use Background in your feature file if every scenario in a single feature shares common
steps (e.g., login before every scenario).

Example:
Feature: Manage User Profile

Background:
Given User is logged in

Scenario: Update email address


When User goes to profile page
And User updates email
Then Email should be updated successfully

✅ 3. Tags + Hooks Approach

You can use tags like @LoginRequired and handle login/logout in a @Before and
@After hook in your step definitions or hooks class.

Example:
@Before("@LoginRequired")
public void login() {
// Code to perform login
}

@After("@LoginRequired")
public void logout() {
// Code to perform logout
}
Feature file:
gherkin
CopyEdit
@LoginRequired
Scenario: Access dashboard
When User navigates to dashboard
Then Dashboard is displayed

7. What is the purpose of Background in Cucumber, and how is it used?


The Background keyword in Cucumber is used to define common steps that are
repeated at the beginning of every scenario in a feature file.

It helps:

 Avoid duplication
 Make feature files cleaner and more readable

How Background Works:

When Cucumber runs each scenario in the feature file, it automatically executes the
Background steps before each scenario.

Syntax Example:

Feature: User Login and Dashboard Access

Background:
Given User is on the login page
And User enters valid credentials
And User clicks on the login button

Scenario: View dashboard


When User navigates to dashboard page
Then Dashboard should be displayed

Scenario: View profile


When User navigates to profile page
Then Profile page should be displayed

What happens here?

 The steps inside Background will be executed before every scenario in this feature
(View dashboard, View profile).
 So you don’t have to repeat the login steps in each scenario.

8. How do you schedule jobs in Jenkins for continuous integration and testing?
In Jenkins, jobs (also called projects or pipelines) can be scheduled to run automatically
using cron syntax. This helps automate testing, builds, or deployments at specific intervals.

🔧 Steps to Schedule a Jenkins Job

1. Go to Your Jenkins Job

 Open Jenkins dashboard


 Click on the job you want to schedule

2. Click on "Configure"
3. Check "Build periodically" or "Poll SCM"

 You'll see a textbox labeled Schedule where you enter the cron expression

# Cron Syntax in Jenkins

MINUTE HOUR DOM MONTH DOW


Field Description

MINUTE 0-59

HOUR 0-23

DOM Day of month (1-31)

MONTH 1-12 or Jan-Dec

DOW Day of week (0-7 or Sun-Sat)

# Examples

Schedule Cron Syntax Meaning

Every 15 minutes H/15 * * * * Jenkins runs the job every 15 minutes

Daily at midnight 00*** Runs at 12:00 AM every day

Every Monday at 9 AM 09**1 Runs at 9:00 AM on Mondays

On the 1st of every month 001** Monthly job

H is used to distribute the load evenly across slaves (instead of hardcoding a number). For
example, H/15 spreads out jobs by 15-minute intervals.

9. What are the key differences between a List and a Set in Java?
In Java, List and Set are both interfaces from the Collection framework, but they serve
different purposes:

1. Duplicates:
o List allows duplicate elements.
o Set does not allow duplicates — each element must be unique.
2. Order:
o List maintains insertion order.
o Set generally does not maintain order (HashSet), but LinkedHashSet
preserves insertion order, and TreeSet stores elements in sorted order.
3. Indexing:
o List supports index-based access using methods like get(int index).
o Set does not support indexing.
4. Performance:
o List is slower for operations like contains() because it may involve
linear search.
o HashSet offers better performance for search, insertion, and deletion due to
its underlying hash table.
5. Use Case:
o Use List when you need to maintain order and allow duplicates (e.g., a list
of items in a cart).
o Use Set when you need to ensure uniqueness (e.g., storing unique user IDs or
email addresses).

10. What is the difference between an Array and a Linked List in Java?

The main difference between an Array and a Linked List in Java lies in memory allocation,
access time, and flexibility.

1. Memory Allocation:
o Array uses contiguous memory and has a fixed size. Once declared, its size
cannot be changed.
o Linked List uses non-contiguous memory and is dynamic in size, allowing
elements to be added or removed easily.
2. Access Time:
o Array provides fast random access using an index (O(1)), which makes it
efficient for reading data.
o Linked List requires sequential access (O(n)) to reach a specific element, as
each node points to the next.
3. Insertion and Deletion:
o Array is slower (O(n)) for insertion/deletion because elements need to be
shifted.
o Linked List allows faster insertion and deletion (O(1) at head/tail),
especially when working with pointers.
4. Memory Usage:
o Array uses less memory as it only stores data.
o Linked List uses more memory because it stores both data and a reference
(pointer) to the next node.

Conclusion:

 Use Array when you need fast access and know the size in advance.
 Use Linked List when you need frequent insertions/deletions and flexibility in size.

11. Can you write a Java program to find duplicate characters in a given string?

12. How does the Binary Search algorithm work, and can you explain it with an example?
Binary Search is an efficient algorithm used to find the position of a target element in a sorted
array. It works by repeatedly dividing the search interval in half.

🔍 How Binary Search Works

1. Start with the whole sorted array.


2. Find the middle element of the array.
3. Compare the target value with the middle element:
o If it's equal → target found.
o If target < middle → search the left half.
o If target > middle → search the right half.
4. Repeat steps 2–3 on the new half until the element is found or the interval is empty.

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


A palindrome is a string that reads the same forward and backward, like:

 "madam"
 "racecar"
 "121"

14. What do the HTTP status codes 500 and 401 represent?

HTTP 500 – Internal Server Error

 Meaning: This status code means that something went wrong on the server while
processing the request.
 Cause: It's a generic error when the server encounters an unexpected condition.
 Examples:
o Null pointer exceptions
o Database connection failures
o Application crashes or misconfigurations
✅ Fix is needed on the server-side, not the client.

HTTP 401 – Unauthorized

 Meaning: The request requires authentication, but either:


o No credentials were provided, or
o The credentials were invalid (e.g., wrong username/password or expired
token)
 Cause: User is not logged in or not authenticated.
 Examples:
o Accessing a protected API endpoint without a valid token
o Failing login due to incorrect credentials

✅ Fix this by providing correct authentication, like:

Authorization: Bearer <valid-token>

15. What is the difference between the HTTP methods POST and PUT in
terms of API usage?

When discussing API usage, the core difference between POST and PUT lies in their
semantics regarding resource creation and when discussing API usage, the core difference
between POST and PUT lies in their semantics regarding resource creation and idempotence:

 POST (Create a new resource):


o Purpose: POST is primarily used to create new resources on the server.
o Semantics: When you send a POST request, you are asking the server to
process the enclosed entity (the request body) and, as a result, create a new
resource that is subordinate to the URI you are posting to.
o Idempotence: POST is not idempotent. This means that making the exact
same POST request multiple times will likely result in the creation of multiple,
identical (or very similar) resources on the server. For example, if you POST to
/products with details for a new iPhone, and you send that request three
times, you'll likely end up with three iPhone entries in the database.
o Typical Use Cases:
 Creating a new user account.
 Adding a new item to a shopping cart.
 Submitting a form to create a new blog post.
 Uploading a file.
 PUT (Update or Create/Replace an existing resource):
o Purpose: PUT is used to update an existing resource or to create/replace a
resource at a specific URI.
o Semantics: When you send a PUT request, you are supplying a representation
of a resource that should be stored at the specified URI. If a resource already
exists at that URI, PUT will update or completely replace it with the new
representation provided in the request body. If no resource exists at that URI,
PUT can create it (though this is less common for general "creation" than
POST).
o Idempotence: PUT is idempotent. This is a crucial distinction. Sending the
exact same PUT request multiple times will have the same effect as sending it
once. It will always result in the resource at that specific URI being in the
same state (the state defined by the request body). For example, if you PUT to
/products/123 with updated details for an iPhone, and you send that request
three times, the iPhone with ID 123 will still only exist once and will reflect
the same updated details.
o Typical Use Cases:
 Updating all fields of an existing user's profile.
 Replacing an entire document at a specific URL.
 Creating a resource where the client determines the unique identifier
(e.g., PUT /users/[Link] where "[Link]" is the unique ID).

Analogy:

Think of it like this:

 POST: "Here's some data. Please create a new thing for me with this data, and you
decide where it goes (assign it an ID)." (e.g., "Add a new item to my shopping cart.")
 PUT: "Here's the complete representation of an item. Please ensure that the item at this
specific location/ID matches this representation. If it doesn't exist, create it. If it does,
update/replace it." (e.g., "Update the details of the item with ID 123.")

In Summary:

Feature POST PUT


Update/Replace existing resource, or
Purpose Create new resource(s)
create at specific URI
Idempotence Not idempotent Idempotent
Typically refers to a collection Refers to a specific resource URI (e.g.,
URI
URI (e.g., /users) /users/123)
Client often dictates or provides the
Server's Role Generates the resource ID
resource ID

Other Interview Questions


1. Can you explain your framework architecture?

Yes, I’ve worked on a hybrid automation framework combining the features of Data-
Driven, Keyword-Driven, and Modular frameworks, built using Selenium WebDriver,
TestNG, Maven, and Java.

🔧 Key Components of My Framework:

1. Base Class
o Handles WebDriver setup and teardown (browser initialization, timeouts, etc.).
2. Page Object Model (POM)
o Every page has a dedicated Java class.
o Web elements are defined using @FindBy, and actions are written as
methods.
o It ensures code reusability and maintainability.
3. Utilities
o Utility classes for reusable actions like dropdown handling, waits, file reading,
Excel operations, screenshots, etc.
4. Test Data Management (Data-Driven)
o Test data is maintained in Excel files, accessed using Apache POI.
o Also supports reading data from properties or JSON files.
5. Keyword-Driven Layer (Optional)
o Test actions like click, enterText, verifyText are driven by
keywords from an Excel sheet.
6. TestNG
o Used for test execution, prioritization, grouping, and parallel execution.
o TestNG XML is used for suite configuration.
7. Reporting
o Integrated Extent Reports for generating detailed HTML reports.
o Also logs test steps using Log4j or SLF4J.
8. Maven
o Used for build management and dependency handling via [Link].
9. CI Integration
o The framework is integrated with Jenkins for scheduled and triggered runs.
10. Assertions
o Used both soft and hard assertions using TestNG or AssertJ depending on
test needs.

2. What are the different types of HTTP requests?


HTTP defines several request methods that indicate the desired action to be performed on a
resource. The most commonly used HTTP methods in API testing are:

🔹 1. GET

 Used to retrieve data from the server.


 It is safe and idempotent (doesn’t change server state).
 ✅ Example: GET /users/101

🔹 2. POST

 Used to create a new resource on the server.


 It is not idempotent – multiple requests can create multiple resources.
 ✅ Example: POST /users

🔹 3. PUT

 Used to create or fully update a resource at a known URI.


 It is idempotent.
 ✅ Example: PUT /users/101

🔹 4. PATCH

 Used to partially update a resource.


 Only updates the specified fields.
 ✅ Example: PATCH /users/101

🔹 5. DELETE

 Used to delete a resource from the server.


 It is idempotent.
 ✅ Example: DELETE /users/101

🔹 6. HEAD

 Similar to GET but only retrieves headers, not the body.


 Useful for checking if a resource exists or for metadata.

🔹 7. OPTIONS

 Used to describe the allowed methods on a resource.


 Helps with CORS preflight requests.

🔹 8. TRACE / CONNECT

 Rarely used; mainly for diagnostic or tunneling purposes (e.g., proxies).


3. What’s the difference between PUT and PATCH?

Both PUT and PATCH are used to update resources in a RESTful API, but the key difference
lies in how they update the data:

🔹 PUT – Full Update

 Replaces the entire resource with the new data provided.


 If any field is missing in the request, it may be reset or removed.
 It is idempotent – making the same request multiple times has the same effect.

PATCH – Partial Update

 Updates only the specified fields in the resource.


 It is not necessarily idempotent.

4. Write a Java code to count characters in: "ttessst@innn123ggg!"

JAVA BASIC QUESTIONS


Static Variable and Instance Variable(Non-Static Variable)
1. Instance Variable (Non-Static Variable)

 Definition: Variables declared inside a class but outside any method, and without
the static keyword.
 Belongs to: An object (instance) of the class.
 Memory Allocation: Separate copy for each object is created in the heap memory.
 Access: Accessed using object reference.
 Lifecycle: Exists as long as the object exists.

class Example {

int instanceVar = 10; // Instance variable

public static void main(String[] args) {

Example obj1 = new Example();

Example obj2 = new Example();

[Link] = 20;

[Link]([Link]); // Output: 20 (changed for obj1)

[Link]([Link]); // Output: 10 (separate copy for obj2)

2. Static Variable (Class Variable)

 Definition: Variables declared inside a class with the static keyword.


 Belongs to: The class, not to individual objects.
 Memory Allocation: Single copy is created in the method area and shared among all
objects.
 Access: Accessed using class name or object reference (preferred via class name).
 Lifecycle: Exists as long as the class is loaded in memory.

class Example {

static int staticVar = 100; // Static variable

public static void main(String[] args) {

Example obj1 = new Example();

Example obj2 = new Example();

[Link] = 200;
[Link]([Link]); // Output: 200

[Link]([Link]); // Output: 200 (shared)

[Link]([Link]); // Output: 200 (via class name)

1) What are static blocks and static initializers in Java?

1) Static Block

 A static block is a block of code inside a class declared using the static keyword.
 It runs only once, when the class is loaded into memory (before the main method
or object creation).
 Commonly used to initialize static variables or perform one-time setup tasks.

Syntax:

class Example {

static int count;

// Static Block

static {

[Link]("Static block executed");

count = 10; // Initializing static variable

public static void main(String[] args) {

[Link]("Main method executed");

[Link]("Count = " + count);

}}

Key Points:

 Executes only once when the class is first loaded.


 Runs before the main method or any object creation.
 Mainly used for static variable initialization or configuration setup.

2) Static Initializer

 A static initializer refers to the process of initializing static variables using either a
static block or inline initialization.
 It can be a single line assignment or multiple statements inside a static block.

Example of Static Initializer:

class Example {

static int a = 5; // Static initializer (inline)

static int b;

// Static initializer block

static {

b = 10; // Complex initialization

[Link]("Static initializer block executed");

public static void main(String[] args) {

[Link]("a = " + a);

[Link]("b = " + b);

Key Points:

 Static initializers can be:


o Inline assignment (e.g., static int a = 10;)
o Static block (for complex logic).
 Used for initializing static variables before any object or method is used.

2) How to call one constructor from the other constructor Or


(Constructor Chaining)?
In Java, we can call one constructor from another in two ways:

 this() → to call another constructor in the same class.


 super() → to call a constructor from the parent class.

1) Calling a Constructor in the Same Class using this()

 this() must be the first statement in the constructor.


 Used to reuse initialization code and avoid duplication.

Example:

class Example {
int a;
int b;

// Constructor 1
Example() {
this(10, 20); // Calls Constructor 2
[Link]("Default constructor called");
}

// Constructor 2
Example(int x, int y) {
a = x;
b = y;
[Link]("Parameterized constructor called:
a=" + a + ", b=" + b);
}

public static void main(String[] args) {


Example obj = new Example(); // Calls Constructor 1 →
Constructor 2
}
}

2) Calling a Parent Class Constructor using super()

 super() must also be the first statement in the constructor.


 If not specified, Java automatically calls the parent’s default constructor.
 Used in constructor chaining across inheritance.

Example:

class Parent {
Parent(String msg) {
[Link]("Parent constructor: " + msg);
}
}
class Child extends Parent {
Child() {
super("Hello from Child"); // Calls Parent's
constructor
[Link]("Child constructor");
}
}

public class Main {


public static void main(String[] args) {
Child obj = new Child();
}
}

Key Rules for Both

1. this() and super() must be the first statement in the constructor.


2. You cannot use both in the same constructor.
3. Constructor chaining improves code reuse and readability.

3) What is method overriding in java?

Definition:
Method overriding occurs when a subclass provides its own implementation for a method
that is already defined in its parent class.
The overridden method in the subclass must have:

 Same method name


 Same parameter list
 Same or compatible return type

Key Points

1. Inheritance is mandatory — Overriding happens only between a superclass and its


subclass.
2. The access level cannot be more restrictive than the overridden method (but can be
more permissive).
3. The return type must be the same or a subtype (covariant return type).
4. The overridden method cannot have a lower access modifier.
5. @Override annotation is optional but recommended (helps detect errors at compile
time).
6. Static, private, and final methods cannot be overridden.
7. Constructors cannot be overridden.

Example:

class Animal {
void sound() {

[Link]("Animal makes a sound");

class Dog extends Animal {

@Override

void sound() {

[Link]("Dog barks");

public class Main {

public static void main(String[] args) {

Animal obj = new Dog(); // Reference is Animal, object is Dog

[Link](); // Output: Dog barks

How It Works:

 Here, sound() is defined in Animal and overridden in Dog.


 At runtime, the JVM decides which method to call based on the actual object (Dog),
not the reference type (Animal).
 This is an example of dynamic method dispatch.

4) What is super keyword in java?


'super' refers to the immediate parent class object.
It is used to access parent class variables, methods, and
constructors.

Find Data in a Specific Cell


//table[@id='tbl1']//tr[3]/td[2]
Explanation: This XPath locates the data in row 3 and column 2
within the table that has an ID tbl1.

Find a Cell with Specific Text


//table[@id='tbl1']//td[text()='Sample Data']
Explanation: This XPath targets the ‘td’ element that contains the
exact text “Sample Data” in the table with ID tbl1.

---
Creating Dynamic XPaths
Using contains(): Example: //input[contains(@id, 'username')]

Using starts-with(): Example: //button[starts-with(@name, 'submit')]

Using text(): Example: //a[text()='Learn More']

Combining Conditions: Logical operators like 'and' or 'or'


Example: //input[@type='text' and contains(@placeholder, 'email')]

Using XPath Axes: Axes (such as parent::, following-sibling::,


ancestor::)
Example: //label[text()='Password']/following-sibling::input

Indexing: Example: (//button[@class='submit'])[2]

🔥 MOST IMPORTANT INTERVIEW DIFFERENCE


Axis What it selects

All nodes after current


following
node

All nodes before


preceding
current node

following-sibling Only next siblings

preceding-sibling Only previous siblings

---
Method overloading - Method overloading allows multiple methods with
the same name but different parameter lists in the same class,
enabling compile-time polymorphism.
8️
⃣ Can we overload static methods?
Yes, static methods can be overloaded.
9️
⃣ Can we overload final methods?
Yes
👉 final prevents overriding, not overloading.

Method overriding - if child class has same method as declared in


the parent class, it is known as method overriding.
8️
⃣ Can we override static methods?
No. While you can write a method with the exact same signature in a
child class, it is not overriding; it is called Method Hiding.

Method Hiding: If a child class defines a static method with the


same signature as one in the parent, the child's version "hides" the
parent's. The version that runs depends on the reference type you
use.

class Parent {
static void display() { [Link]("Parent Static"); }
}

class Child extends Parent {


static void display() { [Link]("Child Static"); }
}

// Usage:
Parent obj = new Child();
[Link](); // Output: "Parent Static" (because the reference
type is Parent)
---
🔥this - 'this' refers to the current object of the class.
It is mainly used to differentiate instance variables from local
variables, and to call current class methods or constructors.

🔥Super - 'super' refers to the immediate parent class object.


It is used to access parent class variables, methods, and
constructors.

1️
⃣ final (Keyword) - final is a keyword used to restrict
modification.
Uses of final - 1. final variable
2. final method
3. final class

2️
⃣ finally (Block) - finally is a block used with try-catch that
always executes, whether an exception occurs or not.
Important Rules of finally -
[Link] even if exception is not handled
[Link] for cleanup: closing files, DB connections
[Link] NOT execute if [Link]() is called
3️
⃣ finalize() (Method) - finalize() is a protected method of Object
class
It is called by Garbage Collector before destroying an object.
Important Points about finalize() -
[Link] automatically by GC
[Link] reliable
[Link] (Java 9 onwards)
[Link] using in real applications

1️⃣ Local Variables - Variables declared inside a method,


constructor, or block.
class Test {
void display() {
int x = 10; // local variable
[Link](x);
}
}

2️⃣ Instance Variables (Non-Static Variables) - Variables declared


inside a class but outside methods, without static.
class Test {
int x = 20; // instance variable
}

3️⃣ Static Variables (Class Variables) - Variables declared with


static keyword.
They belong to the class, not the object.
class Test {
static int count = 0;
}

---
Common Interview Traps

❓ Can we achieve 100% abstraction in Java?


✔ Yes, using interfaces

❓ Does Java support multiple inheritance?


❌ Using classes, ✔ using interfaces

❓ Can constructor be overridden?


❌ No

❓ Can static methods be overridden?


❌ No (they are hidden)

OOPS in Automation (Real-Time Example)

WebDriver driver = new ChromeDriver();


1. Abstraction → WebDriver interface
2. Polymorphism → driver reference
3. Encapsulation → internal browser logic
---
OOPS in Java
1️
⃣ Encapsulation - Wrapping data and methods together into a single
unit (class) and restricting direct access to data.
Why Needed -
1. Data security
2. Controlled access
3. Validation logic

2️⃣ Inheritance - One class acquires properties and behavior of


another class using extends.
class Animal {
void sound() {
[Link]("Animal sound");
}
}
class Dog extends Animal {
void bark() {
[Link]("Dog barking");
}
}

3️
⃣ Polymorphism - Ability of an object to behave differently in
different situations.
A. Compile-time (Method Overloading)
B. Runtime (Method Overriding)

4️
⃣ Abstraction - Hiding implementation details and showing only
essential features.
A. Abstract Class
B. Interface
Abstract class provides partial abstraction with state, while
interface provides full abstraction and supports multiple
inheritance.

Real-Time Automation Example (Selenium) - WebDriver driver = new


ChromeDriver();
| Concept | Used |
| -------------- | ---------------- |
| Interface | WebDriver |
| Implementation | ChromeDriver |
| Polymorphism | driver reference |
---

Tricky Interview Questions

❓ Can abstract class have main method?


✔ Yes

❓ Can interface have main method?


✔ Yes (Java 8+)

❓ Can abstract class implement interface?


✔ Yes

❓ Can interface extend another interface?


✔ Yes (multiple)

❓ Can abstract class be final?


❌ No
---

You might also like