String and Appium
String and Appium
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.
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"
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, !]
Interview Theory
Memory More memory-efficient (only array More memory usage (due to storing
Consumption overhead) previous/next pointers)
2. Difference Between HashMap and TreeMap
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
Used inside the method to Used in the method signature to handle exceptions that
Usage
throw an exception may be thrown during method execution
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
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 have fields with various access modifiers All fields are public, static, and
Access Modifiers
(private, protected) final by default
Does not guarantee any order of Maintains elements in sorted order (natural
Ordering
elements or custom)
Used to access parent class methods or Used to refer to the current class
Usage
constructors instance
Accessing Used to access parent class fields or Used to access current class fields or
Members methods methods
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
Used for inter-thread communication Used to pause the execution of the current
Usage
and synchronization thread for a specified time
Effect on Releases the lock and puts the thread Does not release the lock and just pauses
Thread in a waiting state the thread
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
Thread
Not thread-safe Not thread-safe
Safety
Best for constant or infrequent string Best for single-threaded environments with
Usage
manipulations frequent modifications
Can hold elements of any type Can hold only objects, not primitive types (can use
Type
(primitive or object) wrappers like Integer for int)
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)
Inherited by subclasses
Inherited by Not inherited by Not inherited by
Inheritance in the same package or
subclasses subclasses subclasses
different package
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
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);
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
- Alternatively, if you installed Appium Desktop, you can start the server via the GUI.
Example::
import org.openqa.selenium.interactions.Actions;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import io.appium.java_client.AppiumDriver;
// 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();
}
// Zoom In Gesture
public void zoomInGesture() {
Actions actions = new Actions(driver);
actions.moveByOffset(-200, -200).moveByOffset(100, 100).perform();
}
}
doubleClick() :
actions.doubleClick(element).perform();
multiAction.perform();
** Touch Gestures::-
Using the TouchAction class, you can simulate gestures like pinch, zoom, or swipe
ID By.id("id_value")
Accessibility ID MobileBy.AccessibilityId("accessibility_id")
XPath By.xpath("//tag[@attribute='value']")
Name By.name("name_value")
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.
// 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");
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 {
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());
}
// 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());
@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);
}
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:**
- **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:**
- **Advantages:**
- Easy to use and understand.
- Suitable for elements with meaningful names.
- **Disadvantages:**
- Names are not always unique.
- Performance is slightly slower than `ID`.
**Example:**
- **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.
**Example:**
- **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:**
- **Advantages:**
- Easy to read and implement.
- Works well for static links.
- **Disadvantages:**
- Fails if link text changes or is dynamic.
- Case-sensitive.
**Example:**
- **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`.
**Example:**
- **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 (Following-Sibling):**
- **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.
---
**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')]"));
By understanding and addressing these exceptions, you can create robust and error-resistant
Selenium test scripts.