0% found this document useful (0 votes)
13 views34 pages

String and Appium

The document provides a comprehensive overview of various Java concepts, including string methods, data structures like ArrayList and LinkedList, and differences between key Java features such as exceptions and access modifiers. It outlines the functionalities and performance characteristics of different collections and data types, as well as the distinctions between method overloading and overriding. Additionally, it discusses thread safety, memory allocation, and the usage of Java constructs in programming.

Uploaded by

kailas
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)
13 views34 pages

String and Appium

The document provides a comprehensive overview of various Java concepts, including string methods, data structures like ArrayList and LinkedList, and differences between key Java features such as exceptions and access modifiers. It outlines the functionalities and performance characteristics of different collections and data types, as well as the distinctions between method overloading and overriding. Additionally, it discusses thread safety, memory allocation, and the usage of Java constructs in programming.

Uploaded by

kailas
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

String

1. length()
Returns the length of the string.
String str = "Hello, World!";
int length = str.length(); // length = 13

2. charAt(int index)
Returns the character at the specified index.

String str = "Hello, World!";


char ch = str.charAt(1); // ch = e

3. substring(int beginIndex, int endIndex)


Extracts a substring from the given string, starting at beginIndex and ending at endIndex (excluding
endIndex).
String str = "Hello, World!";
String sub = str.substring(0, 5); // sub = "Hello"

4. indexOf(String str)
Returns the index of the first occurrence of the specified substring.
String str = "Hello, World!";
int index = str.indexOf("World"); // index = 7

5. lastIndexOf(String str)
Returns the index of the last occurrence of the specified substring.
String str = "Hello, World!";
int lastIndex = str.lastIndexOf("o"); // lastIndex = 8
6. toUpperCase()
Converts all characters in the string to uppercase
String str = "Hello, World!";
String upper = str.toUpperCase(); // upper = "HELLO, WORLD!"

7. toLowerCase()
Converts all characters in the string to lowercase.
String str = "Hello, World!";
String lower = str.toLowerCase(); // lower = "hello, world!"

8. trim()
Removes leading and trailing whitespace from the string.
String strWithSpaces = " Hello ";
String trimmed = strWithSpaces.trim(); // trimmed = "Hello"

9. replace(char oldChar, char newChar)


Replaces all occurrences of oldChar with newChar.
String str = "Hello, World!";
String replaced = str.replace(o, a); // replaced = "Hella, Warld!"

10. replaceAll(String regex, String replacement)


Replaces all occurrences that match the regular expression regex with the replacement string.
String str = "Hello, World!";
String replacedAll = str.replaceAll("\\s+", "-"); // replacedAll = "Hello,-World!"

11. split(String regex)


Splits the string around matches of the given regular expression and returns an array of substrings.
String str = "Hello, World!";
String[] parts = str.split(", "); // parts = ["Hello", "World!"]
12. concat(String str)
Concatenates the specified string to the end of this string.
String greeting = "Hello, ";
String result = greeting.concat("World!"); // result = "Hello, World!"

13. equals(Object obj)


Compares the string to the specified object for equality.
String str = "Hello, World!";
boolean isEqual = str.equals("Hello, World!"); // isEqual = true

14. equalsIgnoreCase(String anotherString)


Compares the string to another string, ignoring case differences.
String str = "Hello, World!";
boolean isEqualIgnoreCase = str.equalsIgnoreCase("hello, world!"); // isEqualIgnoreCase = true

15. startsWith(String prefix)


Checks if the string starts with the specified prefix.
String str = "Hello, World!";
boolean starts = str.startsWith("Hello"); // starts = true

16. endsWith(String suffix)


Checks if the string ends with the specified suffix.
String str = "Hello, World!";
boolean ends = str.endsWith("World!"); // ends = true

17. compareTo(String anotherString)


Compares the string with another string lexicographically.
String str = "Hello, World!";
int result = str.compareTo("Hello, World!"); // result = 0 (equal)
18. matches(String regex)
Checks if the string matches the given regular expression.
String str = "Hello, World!";
boolean isMatch = str.matches(".*World.*"); // isMatch = true

19. toCharArray()
Converts the string to a new character array.
String str = "Hello, World!";
char[] chars = str.toCharArray(); // chars = [H, e, l, l, o, ,, , W, o, r, l, d, !]

20. join(CharSequence delimiter, CharSequence... elements)


Joins multiple strings with the specified delimiter.
String joined = String.join("-", "Hello", "World"); // joined = "Hello-World"

Interview Theory

1. Difference Between `ArrayList` and `LinkedList :

Feature ArrayList LinkedList

Data Structure Dynamic array Doubly linked list

Faster for accessing elements by Slower for accessing elements by index


Access Time
index (O(1)) (O(n))

Slower when inserting/removing Faster for insertion/removal (O(1)) at the


Insertion/Deletion
elements (O(n)) ends

Memory More memory-efficient (only array More memory usage (due to storing
Consumption overhead) previous/next pointers)
2. Difference Between HashMap and TreeMap

Feature HashMap TreeMap

Implementation Based on a hash table Based on a red-black tree

Maintains elements in sorted order (natural


Ordering Does not guarantee order of elements
or custom)

Performance Faster for basic operations (O(1)) Slower for basic operations (O(log n))

Allows one null key and multiple Does not allow null keys but allows null
Null Handling
null values values

3. Difference Between String, StringBuilder, and StringBuffer

Feature String StringBuilder StringBuffer

Immutable (cannot be Mutable (can be modified after Mutable (can be modified


Mutability
changed once created) creation) after creation)

Thread Thread-safe (synchronized


Not thread-safe Not thread-safe
Safety methods)

Slower for repeated Faster (no synchronization Slower (due to


Performance
modifications overhead) synchronization)

Best for constant or Best for single-threaded Best for multi-threaded


Usage infrequent string environments with heavy environments with string
changes string manipulation manipulation

4. Difference Between throw and throws

Feature throw throws

Used to explicitly throw an Used in method signatures to declare exceptions it


Definition
exception in code might throw

Used inside the method to Used in the method signature to handle exceptions that
Usage
throw an exception may be thrown during method execution

Can throw any exception


Scope Can only declare exceptions in the method signature
type at any point

Directly throws an exception Does not throw the exception itself, just declares it for
Functionality
to the runtime handling
Difference Between == and .equals() in Java

Feature == Operator .equals() Method

Compares memory references


Purpose Compares actual content of objects
(address comparison)

Used for primitive types and object Used for object content comparison (typically
Usage
reference comparison overridden in custom classes)

Default For objects, compares the memory By default, compares memory location unless
Behavior location, not content overridden

Can be overridden to define custom equality


Overriding Cannot be overridden
logic

Difference Between Abstract Class and Interface

Feature Abstract Class Interface

Can have only abstract methods


Methods Can have both abstract and concrete methods
(before Java 8)

Multiple Can implement multiple


Can extend only one class
Inheritance interfaces

Constructor Can have constructors Cannot have constructors

Can have fields with various access modifiers All fields are public, static, and
Access Modifiers
(private, protected) final by default

Difference Between HashSet and TreeSet

Feature HashSet TreeSet

Implementation Based on a hash table Based on a red-black tree

Does not guarantee any order of Maintains elements in sorted order (natural
Ordering
elements or custom)

Faster for operations (O(1) for basic


Performance Slower for basic operations (O(log n))
operations)

Duplicates Does not allow duplicates Does not allow duplicates


Difference Between super and this in Java

Feature super this

Refers to the current instance of the


Reference Refers to the immediate parent class
class

Used to access parent class methods or Used to refer to the current class
Usage
constructors instance

Used to call the current class


Constructor Call Used to call the parent class constructor
constructor

Accessing Used to access parent class fields or Used to access current class fields or
Members methods methods

Difference Between final, finally, and finalize()

Feature final finally finalize()

Used for variables, methods, Used to define a block of


Called before an object is
Purpose and classes to prevent code that always executes
garbage collected
modification after try-catch

Prevents inheritance, method Used with exception Used for resource cleanup
Usage overriding, and variable handling to ensure (though deprecated in later
reassignment cleanup code is run Java versions)

Does not execute on its own, Always executed after try- Automatically called by the
Execution
used for declaration catch block garbage collector

Can be applied to variables, Applies only to exception Defined in the Object class
Scope
methods, or classes handling blocks and can be overridden

Difference Between wait() and sleep() in Java

Feature wait() sleep()

Used for inter-thread communication Used to pause the execution of the current
Usage
and synchronization thread for a specified time

Thread Must be called from a synchronized


Does not require synchronization
Ownership context (lock required)

Effect on Releases the lock and puts the thread Does not release the lock and just pauses
Thread in a waiting state the thread

The waiting time is generally The sleep duration is specified as a time


Duration
indefinite unless notified interval in milliseconds
Difference Between Method Overloading and Method Overriding

Feature Method Overloading Method Overriding

Defining multiple methods with the same Redefining a method in the subclass
Definition name but different parameter lists in the that is already defined in the parent
same class class

Compile- Compile-time polymorphism (resolved at Run-time polymorphism (resolved at


time/Run-time compile time) runtime)

Must have the same return type (or


Return Type Can have different return types
subtype)

Access Must have the same or more


Can have different access modifiers
Modifiers accessible access modifier

Difference Between String and StringBuilder

Feature String StringBuilder

Immutable (cannot be changed after


Mutability Mutable (can be modified after creation)
creation)

Slower for repeated modifications


Performance Faster (modifies the existing object)
(creates new objects)

Thread
Not thread-safe Not thread-safe
Safety

Best for constant or infrequent string Best for single-threaded environments with
Usage
manipulations frequent modifications

Difference Between Array and ArrayList in Java

Feature Array ArrayList

Fixed size, cannot change once


Size Dynamic size, can grow or shrink as needed
defined

Can hold elements of any type Can hold only objects, not primitive types (can use
Type
(primitive or object) wrappers like Integer for int)

Faster for accessing elements


Performance Slower for accessing elements compared to an array
(O(1))

Flexibility Less flexible (fixed length) More flexible (allows adding/removing elements)
Difference Between public, private, protected, and default Access Modifiers

Default (no
Feature public private protected
modifier)

Accessible from
anywhere (within Accessible only Accessible within the Accessible only
Visibility the class, package, within the same same package and by within the same
subclass, and other class subclasses package
packages)

Used for fields,


Used for methods, Used for fields, Used when no
methods, or
fields, or classes methods, or access modifier is
constructors meant to
Usage meant to be constructors that are specified,
be accessed within the
universally not accessible accessible within
package and by
accessible outside the class the package
subclasses

Inherited by subclasses
Inherited by Not inherited by Not inherited by
Inheritance in the same package or
subclasses subclasses subclasses
different package

Most restrictive, Less restrictive than


Least restrictive, No access outside
Security limiting access to the private, more
allowing full access the package
class only restrictive than public

Difference Between List, Set, and Map in Java

Feature List Set Map

Allows duplicate Does not allow Does not allow duplicate keys (but
Duplicates
elements duplicate elements allows duplicate values)

Maintains insertion Does not maintain Maintains key-value pairs, order is not
Ordering order (e.g., order (e.g., guaranteed unless LinkedHashMap or
ArrayList) HashSet) TreeMap

Does not allow


Allows accessing
Access accessing elements Allows access by key and returns value
elements by index
by index

Based on an array or Based on a hash Based on a hash table, tree, or linked


Implementation
linked list table or tree list
Difference Between public static void main and private static void main
Feature public static void main private static void main
Can be accessed from anywhere in the Can only be accessed within the class it's
Access
application defined in
Entry point for the program (commonly Does not serve as the entry point for the
Execution
used) program
Required for the JVM to recognize the Not recognized by the JVM as an entry point,
Visibility
method and run the program thus the program will not start
Standard entry method for Java Used for testing, not typically used for
Usage
applications program execution
Difference Between Checked Exception and Unchecked Exception
Feature Checked Exception Unchecked Exception
An exception that is checked at compile- An exception that is not checked at compile-
Definition
time time
Subtypes of Exception but not
Subtypes Subtypes of RuntimeException
RuntimeException
Must be handled using try-catch or
Can be handled optionally, no need to declare
Handling declared in the method signature with
or catch them
throws
NullPointerException,
Examples IOException, SQLException
ArrayIndexOutOfBoundsException
Difference Between Vector and ArrayList
Feature Vector ArrayList
Doubles in size when capacity is Increases by 50% of the current size when
Size Growth
exceeded (automatic resizing) capacity is exceeded
Thread
Thread-safe (synchronized) Not thread-safe (not synchronized)
Safety
Faster than Vector in single-threaded
Performance Slower due to synchronization overhead
environments
Considered a legacy class, part of older Part of the Java Collections Framework
Legacy
versions of Java (introduced in Java 1.2)
Used for general-purpose list
Typically used when thread-safety is a
Usage management when thread safety is not a
priority (rarely used in modern Java)
concern
Difference Between Vector and LinkedList
Feature Vector LinkedList
Based on a dynamic array (similar
Implementation Based on a doubly-linked list
to ArrayList)
Faster for random access (O(1) for
Access Time Slower for random access (O(n) for get/set)
get/set)
Slower for insertions and deletions,
Faster for insertions and deletions (O(1) for
Insertion/Deletion especially in the middle of the list
adding/removing at the ends)
(O(n))
Better for frequent indexing and
Better for frequent additions/removals at
Performance iteration due to its array-like
the ends of the list (e.g., addFirst, addLast)
structure
Difference Between Vector and Stack
Feature Vector Stack
A resizable array implementation of the A LIFO (Last In First Out) stack
Purpose
List interface implementation (extends Vector)
Contains all List interface methods like Contains stack-specific methods like push(),
Methods
add(), get(), remove() pop(), peek()
Used when a resizable array is needed for Used for implementing stack operations
Usage
storing elements (LIFO)
Thread Thread-safe (synchronized, as it extends
Thread-safe (synchronized)
Safety Vector)
Stack vs. Heap in Java

Feature Stack Heap


Memory Memory is allocated in a contiguous Memory is allocated dynamically, and
Allocation block. blocks are scattered.
Stores method calls, local variables, and Stores objects and arrays created using
Memory Type
control flow. new keyword.
Local variables in the stack exist only Objects in the heap persist until they are
Lifetime
during method execution. garbage collected.
Typically smaller in size, limited by the Larger and only limited by the system’s
Size
system's stack size. available memory.
Faster access because of its LIFO (Last Slower access due to dynamic allocation
Access Speed
In, First Out) nature. and garbage collection.
Memory Managed automatically by the system Managed by the JVM through garbage
Management (push/pop operations). collection.
Thread-Specific Each thread has its own stack. All threads share the same heap.
Not involved, as the memory is Objects in the heap are subject to
Garbage
automatically freed when the method garbage collection when no longer
Collection
finishes. referenced.
Feature Stack Heap
Size and Grows dynamically based on memory
Growth Fixed size (system-defined)
availability and demand.

Appium
Fluent Wait:
Fluent Wait in Selenium is a powerful and flexible way to define waiting conditions for web elements.
It allows you to wait for an element with a specific condition while checking for the element's presence
at regular intervals. Unlike Implicit Wait and Explicit Wait, Fluent Wait also allows you to handle
exceptions during the wait period.
Wait<WebDriver> wait = new FluentWait<>(driver)
.withTimeout(Duration.ofSeconds(30))
.pollingEvery(Duration.ofSeconds(5))
.ignoring(NoSuchElementException.class);

Implicit Wait, Explicit Wait, and Fluent Wait :

Featur Implicit Wait Explicit Wait Fluent Wait


e
Wait Global for all elements in the Specific to an Specific to an individual element
Scope WebDriver instance individual element
Timeo Fixed timeout for all elements Custom timeout Custom timeout and polling
ut for each element frequency for each element
Pollin No polling interval (waits for the No polling interval Custom polling interval (checks
g full timeout) (just waits for the periodically)
Interva condition)
l
Except Doesn't handle exceptions Can handle Can specify which exceptions to
ion exceptions like ignore during polling
Handli NoSuchElementE
ng xception
Use Simple cases, static elements When specific Complex scenarios with dynamic
Case conditions need to content and flexible conditions
be waited for
Syntax driver.manage().timeouts().impl WebDriverWait Wait<WebDriver> wait = new
icitlyWait(10, wait = new FluentWait<>(driver)<br>
TimeUnit.SECONDS); WebDriverWait(dr .withTimeout(Duration.ofSeconds
iver, (30))<br>
Duration.ofSecon .pollingEvery(Duration.ofSecond
ds(10)); s(5))<br>
.ignoring(NoSuchElementExcepti
on.class);<br> WebElement
element = wait.until(driver ->
driver.findElement(By.id("elemen
tId")));
Q.How to configure Appium in Windows
To configure Appium on a Windows machine, follow these steps:

1. Install Java Development Kit (JDK)


- Download and install [JDK](https://www.oracle.com/java/technologies/javase-downloads.html).
- Set the `JAVA_HOME` environment variable:
1. Right-click on "This PC" or "My Computer" > Properties > Advanced system settings >
Environment Variables.
2. Under "System variables", click "New" and set:
- `JAVA_HOME` = `C:\Program Files\Java\jdk-<version>`
3. Update the `Path` variable to include `JAVA_HOME`:
- Add `%JAVA_HOME%\bin` to the `Path`.

2. Install Android Studio


- Download and install [Android Studio](https://developer.android.com/studio).
- During installation, ensure you install the Android SDK, SDK Platform, and Android Virtual Device
(AVD).
- Set the `ANDROID_HOME` environment variable:
1. Under "System variables", click "New" and set:
- `ANDROID_HOME` = `C:\Users\<your-username>\AppData\Local\Android\Sdk`
2. Add the following paths to the `Path` variable:
- `%ANDROID_HOME%\platform-tools`
- `%ANDROID_HOME%\tools`
- `%ANDROID_HOME%\tools\bin`

3. Install Node.js
- Download and install [Node.js](https://nodejs.org/).
- After installation, verify with `node -v` and `npm -v` to ensure they are installed correctly.

4. Install Appium
- Open a Command Prompt or PowerShell window and install Appium globally using npm:
bash
npm install -g appium

- To check if Appium is installed, run:


bash
appium -v

5. Install Appium Doctor


- Install Appium Doctor to verify if all dependencies are correctly configured:
bash
npm install -g appium-doctor

- Run Appium Doctor:


bash
appium-doctor

It will check your environment and report any missing dependencies.

6. Install Appium Desktop (Optional)


- Download and install [Appium Desktop](https://appium.io/downloads.html) for a GUI interface to
interact with Appium.
- This step is optional, but it provides a useful interface for inspecting elements and running sessions.

7. Install Required Android Drivers


- Run the following command to install Android drivers in Appium:
bash
appium driver install uiautomator2

8. Set Up Android Emulator or Device


- If you want to run tests on an Android emulator, launch Android Studio and create a new Virtual
Device (AVD).
- If you're using a real Android device, enable Developer Options and USB Debugging on the device,
then connect it via USB.

9. Start Appium Server


- You can start the Appium server from the command line with the following:
bash
appium

- Alternatively, if you installed Appium Desktop, you can start the server via the GUI.

10. Write Test Scripts


- Install the Appium client for your preferred language (e.g., Java, Python, JavaScript).
- For Java, add the following dependencies in your `pom.xml` (if using Maven):
xml
<dependency>
<groupId>io.appium</groupId>
<artifactId>java-client</artifactId>
<version>8.3.0</version>
</dependency>

11. Verify Setup


- Once everything is configured, you can write a simple script to launch an app on an emulator or real
device to verify the setup.

Required dependencies for appium setup


1. Appium Java Client
 Name: io.appium:java-client
 Latest Version: 8.3.0 (as of November 2024)
2. Selenium WebDriver
 Name: org.seleniumhq.selenium:selenium-java
 Latest Version: 4.10.0 (as of November 2024)
3. TestNG (Optional)
 Name: org.testng:testng
 Latest Version: 7.7.0 (as of November 2024)
4. Jackson Databind (for JSON parsing)
 Name: com.fasterxml.jackson.core:jackson-databind
 Latest Version: 2.15.2 (as of November 2024)
5. Appium Android Driver
 Name: io.appium:appium-uiautomator2-driver
 Latest Version: 5.0.0 (as of November 2024

Q. Switching from Native Context to Web Context


When testing a hybrid app (one that contains both native and web views), you might need to interact
with a web view, such as an embedded browser (e.g., a WebView element). To switch from the native
context to the web view context, you use the context() method to switch.
// Get all available contexts
Set<String> contextHandles = driver.getContextHandles();
// Switch to the web view context
for (String contextHandle : contextHandles) {
if (contextHandle.contains("WEBVIEW"))
{
driver.context(contextHandle);
// Switch to WebView context break; } }

Q. Switching from Web Context to Native Context


To switch back from the web context to the native context, you can use the context() method again. In
most cases, the native context is named "NATIVE_APP", but you should check the available contexts
first to ensure you're selecting the right one.
// Get all available contexts
Set<String> contextHandles = driver.getContextHandles();
// Switch back to the native context
for (String contextHandle : contextHandles) {
if (contextHandle.equals("NATIVE_APP")) {
driver.context(contextHandle); // Switch back to Native context
break; }}

Q. Handling Contexts Dynamically


Sometimes, it’s not clear how many web views might be present or how many native views there are.
Therefore, it's a good practice to dynamically switch contexts by iterating over the available context
handles and making decisions based on their names.
// Get all available contexts
Set<String> contextHandles = driver.getContextHandles();
// Switch to web view (if exists)
for (String contextHandle : contextHandles) {
if (contextHandle.contains("WEBVIEW")) {
driver.context(contextHandle);
break; }}
// Perform web interactions
driver.findElement(By.id("webElementId")).click();
// Switch back to native context
for (String contextHandle : contextHandles) {
if (contextHandle.equals("NATIVE_APP")) {
driver.context(contextHandle);
break;
}}
// Perform native interactions
driver.findElement(By.id("nativeElementId")).click();
Q. Handling Multiple WebViews
If the app has multiple WebViews, you can check for the available WebViews and select the correct one
by matching the context handle.
// Switch to the first available WebView
for (String contextHandle : contextHandles) {
if (contextHandle.contains("WEBVIEW")) {
driver.context(contextHandle);
break;
}}

Q.How to gesture in appium.


In Appium, you can simulate gestures to interact with mobile applications, such as swiping, pinching,
tapping, scrolling, or dragging. Appium provides APIs to perform these gestures through the
TouchAction class and the W3C Actions API.

Using TouchAction (Pre-W3C)


TouchAction is used to perform low-level touch gestures. The TouchAction class allows you to perform
actions like tap, press, move to, wait, release, and perform gestures like swipe, drag, etc.
1.TouchAction touchAction = new TouchAction(driver);
WebElement element = driver.findElement(By.id("elementId"));
touchAction.tap(element).perform();

2. Swipe Gesture (From Point A to Point B)


Point start = new Point(100, 200); // Starting point
Point end = new Point(100, 100); // Ending point
touchAction.press(start).waitAction(Duration.ofMillis(1000)).moveTo(end).release().perform();

3.Drag Gesture (Dragging one element to another)


WebElement fromElement = driver.findElement(By.id("fromElementId"));
WebElement toElement=driver.findElement(By.id(“toElement”));
touchAction.longPress(fromElement).moveTo(toElement).release().perform();

Using W3C Actions (Recommended for newer versions)


The W3C Actions API is more flexible and is now the preferred method for most gestures in Appium. This API allows you to
chain actions together and is more powerful compared to TouchAction

Example::

import org.openqa.selenium.interactions.Actions;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import io.appium.java_client.AppiumDriver;

public class GesturesExample {

private AppiumDriver driver;

public GesturesExample(AppiumDriver driver) {


this.driver = driver;
}

// Tap Gesture
public void tapGesture(WebElement element) {
Actions actions = new Actions(driver);
actions.click(element).perform();
}
// Swipe Gesture (Using W3C Actions API)
public void swipeGesture(WebElement element) {
Actions actions = new Actions(driver);
actions.clickAndHold(element).moveByOffset(100, 0).release().perform(); // Swipe right
}

// Scroll Gesture
public void scrollGesture(WebElement element) {
Actions actions = new Actions(driver);
actions.moveToElement(element).scrollToElement(element).perform();
}

// Pinch Gesture (Zoom Out)


public void pinchGesture() {
Actions actions = new Actions(driver);
actions.moveByOffset(200, 200).moveByOffset(-100, -100).perform();
}

// Zoom In Gesture
public void zoomInGesture() {
Actions actions = new Actions(driver);
actions.moveByOffset(-200, -200).moveByOffset(100, 100).perform();
}
}

doubleClick() :
actions.doubleClick(element).perform();

** Multi-Touch Actions (Pinch, Zoom, etc.) ::


You can perform multi-touch gestures using multiple TouchAction objects.
TouchAction firstFinger = new TouchAction(driver)
.press(PointOption.point(100, 100))
.moveTo(PointOption.point(150, 150))
.release();

TouchAction secondFinger = new TouchAction(driver)


.press(PointOption.point(200, 200))
.moveTo(PointOption.point(250, 250))
.release();

MultiTouchAction multiAction = new MultiTouchAction(driver)


.add(firstFinger)
.add(secondFinger);

multiAction.perform();

** Touch Gestures::-
 Using the TouchAction class, you can simulate gestures like pinch, zoom, or swipe

TouchAction action = new TouchAction(driver)


.press(PointOption.point(100, 200)) // Start of pinch
.moveTo(PointOption.point(200, 300)) // End of pinch
.release();
action.perform();
Appium locators
In Appium, locators are used to find elements on mobile applications (both native and web). Appium
supports a wide variety of locators, including standard Selenium locators and mobile-specific ones.
Locator Type Syntax

ID By.id("id_value")

Accessibility ID MobileBy.AccessibilityId("accessibility_id")

XPath By.xpath("//tag[@attribute='value']")

Class Name By.className("class_name")

Name By.name("name_value")

Tag Name By.tagName("tag_name")

Link Text By.linkText("text_value")

Partial Link Text By.partialLinkText("partial_text")

CSS Selector By.cssSelector("css_selector")

UIAutomator (Android) MobileBy.AndroidUIAutomator("new UiSelector().text(\"text\")")

UIAutomation (iOS) MobileBy.iOSUIAutomation(".elements()[\"Text\"]")

Image Locator MobileBy.image("path_to_image")

Predicate (iOS) MobileBy.iOSUIAutomation(".elements()[\"Submit\"]")

Class Chain (iOS) MobileBy.iOSClassChain("**/XCUIElementTypeButton[name == 'Submit']")

Q. You are automating a native mobile app and need to click a button with the accessibility ID
submit_button. What locator would you use and why?
Locator: MobileBy.AccessibilityId("submit_button")
Explanation: Accessibility IDs are one of the most reliable locators for native mobile apps, especially
for elements like buttons, text fields, and other interactive components. Accessibility IDs are designed
for users with disabilities, so they tend to be unique and stable, making them ideal for automation.

Q. In your test for a mobile web app, you need to locate a button with the class submit-btn. What
locator would you use?
Locator: By.cssSelector(".submit-btn")
Explanation: CSS selectors are widely used for web-based automation, including mobile web apps. The
. denotes a class, so the cssSelector method is used to find the element by class name (submit-btn in this
case). This approach is efficient and works across various browsers.
Q. You are automating a hybrid app with a webview. You need to find a button inside the webview
with the text "Login". Which locator would you choose and why?
Answer:
 Locator: By.xpath("//button[text()='Login']")
Explanation: When dealing with webviews in hybrid apps, XPath is an ideal choice because it allows
you to query the HTML structure of the webview. Using text() in XPath allows for exact text matching,
which makes it easy to locate buttons or links by their visible text.

Question: In a native Android app, you want to click on a button with the resource ID
com.app:id/next_button. Which locator will you use?
Answer:
 Locator: By.id("com.app:id/next_button")
Explanation: The id locator is one of the most efficient and commonly used methods to locate elements
in native mobile apps. In Android, every element on the screen typically has a unique id attribute, which
makes it a reliable choice for locating elements such as buttons or input fields.

Question: You need to click on a link containing the word "Terms" in its text, but the full text is
"Read our Terms and Conditions". Which locator would you use?
Answer:
 Locator: By.partialLinkText("Terms")
Explanation: partialLinkText allows for locating a link based on partial text matching. Since the link
contains the word "Terms" and this matches the partial text, partialLinkText will be able to identify the
link, even if the full text changes slightly (e.g., “Terms and Conditions”).

Question: You are automating a hybrid mobile app and need to find a button with both the class
names btn and primary. Which locator should you use?
Answer:
 Locator: By.cssSelector(".btn.primary")
Explanation: To locate an element with multiple class names, you can combine them in the cssSelector
by separating them with a space (.btn.primary). This syntax targets elements that have both the btn and
primary class names.

Question: You are automating a mobile web app where a modal dialog appears with a button
inside it. The button’s text is dynamically changing, but the id of the button is submit-button.
What locator would you use?
Answer:
 Locator: By.id("submit-button")
Explanation: Even if the text of the button changes dynamically, the id remains constant. Using id as
a locator is ideal in this scenario because it's less likely to change during dynamic interactions. It
provides a stable way to locate the button.

Question: You are automating an iOS app, and you need to find a text field with the class name
XCUIElementTypeTextField. What locator will you use?
Answer:
 Locator: MobileBy.iOSClassChain("**/XCUIElementTypeTextField")
Explanation: In iOS, class names are specific to the element types in the UI. The iOSClassChain
method allows you to construct a query for iOS-specific elements. Using XCUIElementTypeTextField
as the class name ensures you're targeting the correct input field.
Question: You need to locate a button inside a LinearLayout in an Android app, and this button
has the text Continue. What locator would you use?
Answer:
 Locator:
By.xpath("//android.widget.LinearLayout//android.widget.Button[@text='Continue']")
Explanation: XPath is great for complex queries involving the hierarchy of elements. In this case, you
use a relative XPath to search for the Button element inside a LinearLayout and then filter by the text
attribute to find the button with the text Continue

Question: You want to automate the interaction with an image that has a specific src in a mobile
web app. What locator would you use?
Answer:
 Locator: MobileBy.image("path_to_image")
Explanation: Appium supports locating elements based on images using the image locator. This locator
can be used to compare a screenshot of the target image with the actual image displayed on the screen.
This is helpful when you need to interact with elements that don’t have textual identifiers but are
recognized visually.

Question: In a native iOS app, you need to click a button whose label changes dynamically based
on user actions. The button's text changes, but it always contains the word "Next". How do you
locate it?
Answer:
 Locator: MobileBy.iOSClassChain("**/XCUIElementTypeButton[label CONTAINS 'Next']")
Explanation: For iOS apps, you can use the iOSClassChain to search for elements based on properties
such as label. In this case, using CONTAINS 'Next' allows you to locate the button even if its label
changes dynamically but still contains the word "Next".

Question: In a hybrid mobile app, you need to find a div element within a specific section with a
particular class attribute. Which locator should you use?
Answer:
 Locator: By.xpath("//section[@class='specific-class']//div")
Explanation: This XPath locator allows you to find a div element inside a section with the class
specific-class. The double slashes // indicate that the div can be found anywhere inside the section
element, making it a flexible locator.

Q. Summary of XPath Functions in Appium:


 contains() – Matches partial values.
 text() – Matches exact text.
 starts-with() – Matches values that start with a given prefix.
 position() – Selects an element based on its position in a list.
 last() – Selects the last element in a set.
 ancestor, descendant, child, parent – Navigates through the XML tree.
 following-sibling, preceding-sibling – Selects sibling elements

// Import necessary libraries


import io.appium.java_client.MobileElement;
import io.appium.java_client.android.AndroidDriver;

// Example for finding elements using different locators


// 1. By ID
MobileElement buttonById = driver.findElementById("com.example:id/button_id");
// 2. By Accessibility ID
MobileElement buttonByAccessibilityId =
driver.findElementByAccessibilityId("contentDescription");

// 3. By XPath
MobileElement buttonByXPath =
driver.findElementByXPath("//android.widget.Button[@text='Click Me']");

// 4. By Class Name
MobileElement buttonByClassName =
driver.findElementByClassName("android.widget.Button");
// 5. By Name
MobileElement buttonByName = driver.findElementByName("Button Name");

// 6. By Tag Name
MobileElement inputFieldByTag = driver.findElementByTagName("input");

// 7. By CSS Selector (for web views)


MobileElement buttonByCssSelector = driver.findElementByCssSelector(".button-class");

** Use Dynamic Locators (e.g., UIAutomator or XCUITest) for Mobile Apps::


For mobile apps, you can use UIAutomator (Android) or XCUITest (iOS) locators, which offer more
advanced locator strategies for handling dynamic content.

driver.findElement(MobileBy.AndroidUIAutomator("new UiSelector().textContains(\"Submit\")"));

driver.findElement(MobileBy.iOSClassChain("**/button[`label == 'Submit'`]"));

Comparison Summary
Locator Strategy Platform Advantages Disadvantages
Cross-platform, reliable,
Accessibility ID Android/iOS Requires developer setup
maintainable
ID (resource-id) Android Fast, stable Android-only, not always available
Class Name Android/iOS Cross-platform, simple Not unique, slower than IDs
Flexible, supports complex
XPath Android/iOS Slow, fragile, platform-dependent
queries
Advanced filtering, optimized Android-only, manual expressions
UI Automator Android
for scrolling needed
iOS Predicate iOS-only, requires NSPredicate
iOS Flexible, efficient
String knowledge
iOS-only, hierarchy knowledge
iOS Class Chain iOS Efficient for nested elements
required
Platform-specific attributes, prone
Text Android/iOS Intuitive, easy to use
to changes
Image Android/iOS Handles custom UI Slow, unreliable
Tag Name Android/iOS Simple, works for unique tags Rarely unique, ambiguous matches
Best Practices:
1. Use Accessibility ID wherever possible for cross-platform stability.
2. Avoid XPath unless necessary, and prefer relative paths.
3. For platform-specific needs, use UI Automator (Android) and iOS Predicate String (iOS).
4. Request developers to include meaningful accessibility IDs or resource-ids in the app.

Q.Selenium Popups:
Summary of Selenium Pop-up Handling:
Pop-up Type Handling Method
Alert Alert alert = driver.switchTo().alert(); alert.accept();
Confirmation
Alert alert = driver.switchTo().alert(); alert.dismiss();
Dialog
Alert alert = driver.switchTo().alert(); alert.sendKeys("Text");
Prompt Dialog
alert.accept();
String parentWindow = driver.getWindowHandle(); Set<String>
New Window/Tab
allWindows = driver.getWindowHandles();
File Upload WebElement uploadElement = driver.findElement(By.id("upload"));
Dialog uploadElement.sendKeys("file_path");
Authentication
driver.get("http://username:[email protected]");
Pop-ups
JavaScript Modal WebElement modalCloseButton =
Dialog driver.findElement(By.className("close")); modalCloseButton.click();
Chrome ChromeOptions options = new ChromeOptions();
Notifications options.addArguments("--disable-notifications");
Q. public class BalancedBracketsWithoutStack {

public static boolean areBracketsBalanced(String expression) {


int roundCount = 0; // Count for '(' and ')'
int squareCount = 0; // Count for '[' and ']'
int curlyCount = 0; // Count for '{' and '}'

for (char ch : expression.toCharArray()) {


// Increment counts for opening brackets
if (ch == '(') {
roundCount++;
} else if (ch == '[') {
squareCount++;
} else if (ch == '{') {
curlyCount++;
}
// Decrement counts for closing brackets
else if (ch == ')') {
if (roundCount == 0) return false; // Unmatched ')'
roundCount--;
} else if (ch == ']') {
if (squareCount == 0) return false; // Unmatched ']'
squareCount--;
} else if (ch == '}') {
if (curlyCount == 0) return false; // Unmatched '}'
curlyCount--;
}
}

// If all counts are zero, brackets are balanced


return roundCount == 0 && squareCount == 0 && curlyCount == 0;
}

public static void main(String[] args) {


String expression = "{[()]}";

if (areBracketsBalanced(expression)) {
System.out.println("Balanced");
} else {
System.out.println("Not Balanced");
}
}
}

MAP
1.Sorting of integer using HashMap
(Using Treemap) (HashMap by Keys Without Using TreeMap)
public void ascendingOrderOfNumberWithoutTreeMap() {
// Initialize a HashMap with integer keys and values // Initialize a HashMap with integer keys and values
HashMap<Integer,Integer>map=new HashMap<Integer, Integer> map = new HashMap<>();
HashMap<>(); map.put(5, 20);
map.put(5, 20); map.put(2, 10);
map.put(2, 10); map.put(8, 40);
map.put(8, 40); map.put(1, 5);
map.put(1, 5);
// Convert the HashMap entries to a List
List<Map.Entry<Integer, Integer>> entryList = new ArrayList<>(map.entrySet());
// Convert the HashMap to a TreeMap to sort by keys
TreeMap<Integer,Integer>sortedMap=new
// Sort the list by keys
TreeMap<>(map);
entryList.sort(Map.Entry.comparingByKey());
// Print the sorted map
// Create a LinkedHashMap to maintain the sorted order
System.out.println("Sorted by keys: " + sortedMap);
LinkedHashMap<Integer, Integer> sortedMap = new LinkedHashMap<>();
}
for (Map.Entry<Integer, Integer> entry : entryList) {
sortedMap.put(entry.getKey(), entry.getValue());
}

// Print the sorted map


System.out.println("Sorted by keys: " + sortedMap);
}
public void descendingOrderOfNumberWithoutTreeMap() {

// Initialize a HashMap with integer keys and values


HashMap<Integer, Integer> map = new HashMap<>();
map.put(5, 20);
map.put(2, 10);
map.put(8, 40);
map.put(1, 5);

// Extract keys and sort them in descending order using Collections.sort with a
custom comparator
List<Integer> keys = new ArrayList<>(map.keySet());
Collections.sort(keys, Collections.reverseOrder());

// Create a LinkedHashMap to store entries in descending order of keys


LinkedHashMap<Integer, Integer> sortedMap = new LinkedHashMap<>();

for (Integer key : keys) {


sortedMap.put(key, map.get(key));
}

// Print the sorted map


System.out.println("Sorted by keys in descending order: " + sortedMap);
}

Sorting of Number using ArrayList:

1. ArrayList Sorting in Ascending Order:

public void SortingInAscendingOrderUsingBubbleSort() {


ArrayList<Integer> numbers = new ArrayList<>();
numbers.add(5);
numbers.add(2);
numbers.add(8);
numbers.add(1);

// Bubble Sort in ascending order


for (int i = 0; i < numbers.size() - 1; i++) {
for (int j = 0; j < numbers.size() - 1 - i; j++) {
if (numbers.get(j) > numbers.get(j + 1)) {
// Swap the elements if they are in the wrong order
int temp = numbers.get(j);
numbers.set(j, numbers.get(j + 1));
numbers.set(j + 1, temp);
}
}
}
// Print the sorted ArrayList
System.out.println("Sorted in ascending order: " + numbers);
}

2. ArrayList Sorting in Descending Order Map

public void SortingInDescendingOrderUsingBubbleSort() {


ArrayList<Integer> numbers = new ArrayList<>();
numbers.add(5);
numbers.add(2);
numbers.add(8);
numbers.add(1);
// Bubble Sort in descending order
for (int i = 0; i < numbers.size() - 1; i++) {
for (int j = 0; j < numbers.size() - 1 - i; j++) {
if (numbers.get(j) < numbers.get(j + 1)) {
// Swap the elements if they are in the wrong order
int temp = numbers.get(j);
numbers.set(j, numbers.get(j + 1));
numbers.set(j + 1, temp);
}
}
}
// Print the sorted ArrayList
System.out.println("Sorted in descending order: " + numbers);
}

@Test
public void countOfCharacterUsingHashMap() {
String s="bengalore";
char[] st=s.toCharArray();
Map<Character,Integer>map=new HashMap<>();

for(Character ss:st) {
if(map.containsKey(ss)) {
int count=map.get(ss);
map.put(ss, count+1);
}else
{
map.put(ss,1);
}
}
System.out.println(map);

@Test
public void countOfStringUsingHashMap() {
String s="bengalore";
String[] st=s.split("");
Map<String,Integer>map=new HashMap<>();

for(String ss:st) {
if(map.containsKey(ss)) {
int count=map.get(ss);
map.put(ss, count+1);
}else
{
map.put(ss,1);
}
}
System.out.println(map);
}

** Convert int to String


To convert an integer to a string, you can concatenate it with an empty string:
Int num=10;
String str = String.valueOf(num);
System.out.println("Integer to String: " + str);

** Convert String to int


To convert a string to an integer, you can use Integer.parseInt():
String str = "456";
int num = Integer.parseInt(str); // Convert String to int
System.out.println("String to Integer: " + num);

**Best Approaches for Locators in Selenium**

Choosing the right locator strategy is crucial for creating robust, maintainable, and efficient Selenium
scripts. Below are the best approaches for identifying web elements using locators, along with their
advantages and disadvantages:

**1. By ID**
- **Best for:** Unique and stable element identification.
- **Why?** Fastest and most reliable locator since IDs are unique to elements.

**Example:**

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

- **Advantages:**
- Simple and direct.
- Fastest among all locator strategies.
- Easy to understand and implement.

- **Disadvantages:**
- Not all elements have unique IDs.
- IDs may dynamically change in some frameworks.
**2. By Name**
- **Best for:** When ID is not available, and `name` attributes are unique.
- **Why?** Provides meaningful and readable locators.

**Example:**

WebElement element = driver.findElement(By.name("search"));

- **Advantages:**
- Easy to use and understand.
- Suitable for elements with meaningful names.

- **Disadvantages:**
- Names are not always unique.
- Performance is slightly slower than `ID`.

**3. By Class Name**


- **Best for:** When elements share common styles or categories.
- **Why?** Useful for identifying elements based on CSS class.

**Example:**

WebElement element = driver.findElement(By.className("btn-primary"));

- **Advantages:**
- Quick for elements with unique class names.
- Useful for styling-based locators.

- **Disadvantages:**
- Classes are often reused for multiple elements.
- Cannot locate complex element hierarchies.

**4. By Tag Name**


- **Best for:** Finding elements by their HTML tag (e.g., `<input>`, `<div>`).
- **Why?** Useful for bulk actions like counting elements.

**Example:**

List<WebElement> elements = driver.findElements(By.tagName("input"));

- **Advantages:**
- Useful for generic operations (e.g., finding all links).
- Can locate all elements of a specific type.

- **Disadvantages:**
- Often too generic, leading to ambiguous results.
- Not suitable for identifying a single element.
**5. By Link Text**
- **Best for:** Finding links by their visible text.
- **Why?** Ideal for hyperlinks with unique, static text.

**Example:**

WebElement element = driver.findElement(By.linkText("Click here"));

- **Advantages:**
- Easy to read and implement.
- Works well for static links.

- **Disadvantages:**
- Fails if link text changes or is dynamic.
- Case-sensitive.

**6. By Partial Link Text**


- **Best for:** Links with long or dynamic text, where a unique substring can be used.
- **Why?** Useful for links with predictable but lengthy text.

**Example:**

WebElement element = driver.findElement(By.partialLinkText("Click"));

- **Advantages:**
- Flexible for links with partially known text.
- Case-insensitive.

- **Disadvantages:**
- Can lead to ambiguity if multiple links share similar substrings.
- Less precise than `linkText`.

**7. By CSS Selector**


- **Best for:** Complex structures and fast locators.
- **Why?** Provides flexible and powerful ways to locate elements.

**Example:**

WebElement element = driver.findElement(By.cssSelector("input[name='username']"));

- **Advantages:**
- Faster than XPath.
- Highly flexible for complex hierarchies.
- Combines multiple attributes or pseudo-classes (e.g., `nth-child`).

- **Disadvantages:**
- Requires familiarity with CSS syntax.
- Can become unreadable for very complex selectors.
**8. By XPath**
- **Best for:** Dynamic and complex hierarchies or elements without unique attributes.
- **Why?** Can navigate through the entire DOM tree.

**Example (Relative XPath):**

WebElement element = driver.findElement(By.xpath("//input[@id='username']"));

**Example (Contains Text):**

WebElement element = driver.findElement(By.xpath("//button[contains(text(),'Submit')]"));

**Example (Following-Sibling):**

WebElement element = driver.findElement(By.xpath("//label[text()='Username']/following-


sibling::input"));

- **Advantages:**
- Extremely versatile.
- Useful when no other attributes are available.
- Supports traversing up, down, or across the DOM.

- **Disadvantages:**
- Slower than `ID` or `CSS Selector`.
- Can become brittle and difficult to maintain.
- Absolute XPath (`/html/body/...`) should be avoided.

**Best Practices for Locators**


1. **Prioritize Unique and Stable Attributes**
- Use `ID` > `Name` > `CSS Selector` > `XPath` in that order of preference.
- Avoid dynamic or auto-generated attributes like `id="element_12345"`.

2. **Minimize Dependency on Layout**


- Avoid absolute XPaths tied to layout changes (`/div[1]/div[2]/...`).

3. **Use Descriptive Locators**


- Use attributes that convey element meaning or purpose (e.g., `data-*` attributes).

4. **Optimize Locator Strategies for Speed**


- Prefer `CSS Selector` over `XPath` for better performance where applicable.

5. **Test Locators Independently**


- Verify the uniqueness of locators using browser developer tools (e.g., Chrome DevTools).

6. **Consider Element Visibility**


- Ensure the element is visible and interactable (e.g., `isDisplayed` or `isEnabled`).
7. **Use Logical Grouping for Repeated Elements**
- Group elements using parent-child relationships or common classes.

**Choosing Between CSS and XPath**


| **Aspect** | **CSS Selector** | **XPath** |
|---------------------- |------------------------- |---------------------------|
| **Speed** | Faster | Slower |
| **Readability** | Compact and clean | Can be verbose |
| **Flexibility** | Limited DOM traversal| Full DOM traversal |
| **Ease of Use** | Familiar CSS syntax | Steeper learning curve |

**Locators in Selenium can throw various exceptions depending on the


situation and the locator's usage.

---

**1. NoSuchElementException**
- **Thrown When:**
The specified element cannot be found on the web page using the provided locator.

- **Common Causes:**
- Incorrect or outdated locator.
- Element takes time to load or render (timing issue).
- Element is not in the DOM (e.g., hidden elements).

- **Example:**
java
WebElement element = driver.findElement(By.id("nonexistentID"));

- **Solution:**
- Ensure the locator is accurate and matches the current DOM structure.
- Use waits (explicit or fluent wait) to allow the element to load.
- Confirm the element is in the visible DOM and not hidden.

---

**2. StaleElementReferenceException**
- **Thrown When:**
A previously located element is no longer valid (e.g., the page is refreshed or the element is
re-rendered).

- **Common Causes:**
- DOM updates after locating the element.
- Use of an old reference to an element after a page refresh or navigation.

- **Example:**
WebElement element = driver.findElement(By.id("dynamicElement"));
driver.navigate().refresh();
element.click(); // Throws StaleElementReferenceException

- **Solution:**
- Re-locate the element after the DOM update.
- Use explicit waits to ensure the DOM is stable.

---

**3.ElementNotVisibleException*(Deprecated,now**ElementNotInteractableException**)
- **Thrown When:**
The element is present in the DOM but is not visible (e.g., `display: none` or outside the
viewport).

- **Common Causes:**
- Hidden elements due to CSS or JavaScript.
- Overlapping elements obstructing the intended element.

- **Example:**
WebElement element = driver.findElement(By.id("hiddenElement"));
element.click(); // Throws ElementNotInteractableException

- **Solution:**
- Use `element.isDisplayed()` to verify visibility before interacting.
- Scroll to the element or remove obstructions programmatically.

---

**4. TimeoutException**
- **Thrown When:**
An explicit wait or fluent wait times out before the element becomes available.

- **Common Causes:**
- Long page load times.
- Incorrect waiting condition or locator.

- **Example:**
WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));
WebElement element =
wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("slowElement")));

- **Solution:**
- Adjust the timeout duration.
- Optimize waiting conditions.
**5. InvalidSelectorException**
- **Thrown When:**
The provided selector syntax is invalid or not supported.

- **Common Causes:**
- Using an incorrect syntax for CSS or XPath.
- Mixing XPath with CSS syntax.

- **Example:**
java
WebElement element = driver.findElement(By.cssSelector("div[@id='example']")); // Invalid

- **Solution:**
- Verify the selector syntax using browser developer tools (e.g., Chrome DevTools).
- Use tools like `XPath Helper` or `Selector Gadget` to validate selectors.

**6. NoSuchFrameException**
- **Thrown When:**
Attempting to switch to a non-existent or invalid frame.

- **Common Causes:**
- Frame is not present in the DOM.
- Incorrect frame locator.

- **Example:**
driver.switchTo().frame("nonexistentFrame");

- **Solution:**
- Ensure the frame exists before switching.
- Use `driver.switchTo().defaultContent()` to return to the main document if necessary.

**7. NoSuchWindowException**
- **Thrown When:**
Attempting to switch to a non-existent or closed browser window.

- **Common Causes:**
- Referencing a window that has already been closed.
- Incorrect window handle.
- **Example:**
driver.switchTo().window("invalidWindowHandle");

- **Solution:**
- Use `driver.getWindowHandles()` to retrieve valid window handles.
- Verify the window is open before switching.
**8. InvalidElementStateException**
- **Thrown When:**
The element is not in a state to perform the requested action (e.g., sending keys to a disabled
input).

- **Common Causes:**
- Disabled input fields.
- Attempting actions on non-interactable elements.

- **Example:**
WebElement element = driver.findElement(By.id("disabledInput"));
element.sendKeys("test"); // Throws InvalidElementStateException

- **Solution:**
- Ensure the element is interactable (`isEnabled()`).
- Check the state of the element before performing actions.

**9. ElementClickInterceptedException**
- **Thrown When:**
Another element intercepts the click action.

- **Common Causes:**
- Pop-ups, modals, or overlays blocking the element.
- Improper positioning of the target element.

- **Example:**
WebElement element = driver.findElement(By.id("button"));
element.click(); // Throws ElementClickInterceptedException

- **Solution:**
- Dismiss pop-ups or overlays programmatically.
- Scroll to the element to ensure it is fully visible.

**10. WebDriverException**
- **Thrown When:**
There’s a generic issue with WebDriver or its interaction with the browser.

- **Common Causes:**
- Issues with the WebDriver setup or browser compatibility.
- Network problems or browser crashes.

- **Solution:**
- Verify the WebDriver version is compatible with the browser.
- Ensure proper WebDriver setup and configurations.
**Best Practices to Avoid Locator Exceptions**
1. **Use Explicit Waits:**
Ensure elements are present, visible, and interactable before interacting with them.
java
WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));
WebElement element =
wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("username")));

2. **Validate Locators:**
Test locators in browser developer tools to confirm their accuracy.

3. **Dynamic Locators:**
Use dynamic XPath or CSS Selectors for elements with changing attributes.
java
WebElement element=driver.findElement(By.xpath("//button[contains(@class, 'submit')]"));

4. **Handle Exceptions Gracefully:**


Wrap actions in `try-catch` blocks to capture and log exceptions.

5. **Page Object Model (POM):**


Use POM to centralize locators, making them easier to update and maintain.

By understanding and addressing these exceptions, you can create robust and error-resistant
Selenium test scripts.

You might also like