Strings are the most used data type in test automation. Page titles, element text, URLs, error messages, test data — all strings. Java's String class has methods for every text operation you need.
public class StringCreation {
public static void main(String[] args) {
// String literal (recommended)
String url = "https://demo-bank.example.com";
// String object (avoid — creates unnecessary object)
String url2 = new String("https://demo-bank.example.com");
// Empty and blank
String empty = "";
String blank = " ";
System.out.println(url.equals(url2)); // true — same content
System.out.println(url == url2); // false — different objects
}
}These are the methods you will use daily in test automation.
public class StringMethods {
public static void main(String[] args) {
String title = " Welcome to Demo Bank ";
// Length and trim
System.out.println(title.length()); // 24 (includes spaces)
System.out.println(title.trim()); // "Welcome to Demo Bank"
System.out.println(title.trim().length()); // 20
// Case conversion
String status = "Pass";
System.out.println(status.toUpperCase()); // "PASS"
System.out.println(status.toLowerCase()); // "pass"
// Checking content
String msg = "Login successful";
System.out.println(msg.contains("successful")); // true
System.out.println(msg.startsWith("Login")); // true
System.out.println(msg.endsWith("failed")); // false
System.out.println(msg.isEmpty()); // false
// Finding and extracting
String email = "admin@testerrank.com";
System.out.println(email.indexOf("@")); // 5
System.out.println(email.substring(6)); // "testerrank.com"
System.out.println(email.substring(0, 5)); // "admin"
}
}| Method | Returns | Automation Use |
|---|---|---|
| length() | int | Verify text is not empty |
| trim() | String | Clean whitespace from element text |
| toUpperCase() / toLowerCase() | String | Case-insensitive comparison |
| contains(str) | boolean | Check if text contains expected word |
| startsWith(str) / endsWith(str) | boolean | Verify URL prefix, file extension |
| equals(str) | boolean | Exact match assertion |
| equalsIgnoreCase(str) | boolean | Case-insensitive assertion |
| indexOf(str) | int | Find position of substring (-1 if not found) |
| substring(begin) / substring(begin, end) | String | Extract part of text |
| replace(old, new) | String | Replace characters or substrings |
| split(regex) | String[] | Split text into parts (CSV, spaces) |
| charAt(index) | char | Get character at position |
public class ReplaceAndSplit {
public static void main(String[] args) {
// Replace
String price = "$1,299.99";
String clean = price.replace("$", "").replace(",", "");
double amount = Double.parseDouble(clean);
System.out.println(amount); // 1299.99
// Split
String csv = "Chrome,Firefox,Safari,Edge";
String[] browsers = csv.split(",");
for (String b : browsers) {
System.out.println("Browser: " + b);
}
// Split with limit
String log = "ERROR: Login failed: invalid password";
String[] parts = log.split(": ", 2);
System.out.println("Level: " + parts[0]); // ERROR
System.out.println("Message: " + parts[1]); // Login failed: invalid password
}
}public class StringCompare {
public static void main(String[] args) {
String expected = "Dashboard";
String actual = "dashboard";
// WRONG — compares references
System.out.println(expected == actual); // may be false
// CORRECT — compares content
System.out.println(expected.equals(actual)); // false (case-sensitive)
System.out.println(expected.equalsIgnoreCase(actual)); // true
// Null-safe comparison (put the known string first)
String pageTitle = null;
// pageTitle.equals("Dashboard"); // NullPointerException!
System.out.println("Dashboard".equals(pageTitle)); // false — no exception
}
}Always put the known string first in equals: "expected".equals(variable) instead of variable.equals("expected"). This prevents NullPointerException if the variable is null.
Strings in Java are immutable — every method returns a NEW string and leaves the original unchanged.
public class Immutability {
public static void main(String[] args) {
String name = "hello";
name.toUpperCase(); // returns "HELLO" but name is still "hello"
System.out.println(name); // "hello"
name = name.toUpperCase(); // reassign to capture the result
System.out.println(name); // "HELLO"
}
}When you need to build a string in a loop, use StringBuilder. It is mutable and much faster than string concatenation in loops.
public class StringBuilderDemo {
public static void main(String[] args) {
StringBuilder report = new StringBuilder();
report.append("Test Report\n");
report.append("===========\n");
String[] tests = {"Login", "Search", "Checkout"};
String[] results = {"PASS", "PASS", "FAIL"};
for (int i = 0; i < tests.length; i++) {
report.append(tests[i]).append(": ").append(results[i]).append("\n");
}
System.out.println(report.toString());
}
}Test Report
===========
Login: PASS
Search: PASS
Checkout: FAILQ: Why is String immutable in Java?
A: String immutability provides three benefits: (1) Security — strings used for passwords, URLs, and file paths cannot be modified after creation. (2) Thread safety — immutable objects are inherently thread-safe since no thread can change the value. (3) String pool optimization — Java caches string literals in a pool; immutability guarantees that sharing a pooled string across multiple references is safe.
Q: What is the String pool?
A: The String pool is a special memory area in the heap where Java stores string literals. When you write String s = "hello", Java first checks the pool — if "hello" already exists, it returns a reference to the existing object instead of creating a new one. This saves memory. new String("hello") bypasses the pool and always creates a new object on the heap, which is why == comparison between a literal and a new String returns false.
Exercise 1: Given the string " Welcome, John Doe! ", write code that: (a) trims it, (b) extracts just the name "John Doe", (c) converts to uppercase, (d) checks if it contains "John".
Exercise 2: Write a program that takes a full email address and prints the username (before @) and domain (after @) separately.
Exercise 3: Build a test result summary using StringBuilder. Loop through 5 test names and statuses, then print the final report with total pass/fail counts.
Answer all 10 questions, then submit to see your score.
1. What does System.out.print("A"); System.out.print("B"); output?
2. Which data type should you use for a test timeout value of 30.5 seconds?
3. What is the output of: int x = 7; int y = 2; System.out.println(x / y);
4. What does (double) 9 / 2 return?
5. Which operator checks if a number is even?
6. What does "Hello".equals(null) return?
7. String s = "test"; s.toUpperCase(); System.out.println(s); — what prints?
8. What does "10,20,30".split(",").length return?
9. Which is the correct way to compare two Strings for equality?
10. What is the output of: System.out.println("Sum: " + 2 + 3);