Chapter 3 covered String basics. This lesson covers advanced patterns you will use daily in automation — regex matching, formatting, joining, and real extraction scenarios.
public class RegexMatch {
public static void main(String[] args) {
String email = "user@test.com";
String phone = "9876543210";
String zipCode = "560001";
// matches() checks if ENTIRE string matches the regex
System.out.println(email.matches(".*@.*\\..*")); // true
System.out.println(phone.matches("\\d{10}")); // true
System.out.println(zipCode.matches("\\d{6}")); // true
// Practical validations
String password = "Test@123";
boolean hasUpper = password.matches(".*[A-Z].*");
boolean hasDigit = password.matches(".*\\d.*");
boolean hasSpecial = password.matches(".*[@#$%^&+=].*");
boolean isLongEnough = password.length() >= 8;
System.out.println("Strong password: " + (hasUpper && hasDigit && hasSpecial && isLongEnough));
}
}public class RegexReplace {
public static void main(String[] args) {
// Remove all non-numeric characters
String price = "$1,299.50";
String cleaned = price.replaceAll("[^0-9.]", "");
System.out.println(cleaned); // 1299.50
// Remove extra whitespace
String messy = " Login Test Suite ";
String clean = messy.trim().replaceAll("\\s+", " ");
System.out.println(clean); // "Login Test Suite"
// Mask sensitive data
String card = "4111-2222-3333-4444";
String masked = card.replaceAll("\\d{4}-\\d{4}-\\d{4}", "****-****-****");
System.out.println(masked); // ****-****-****-4444
}
}public class FormatJoin {
public static void main(String[] args) {
// String.format — same as printf but returns a String
String report = String.format("Test: %s | Status: %s | Time: %.2fs",
"LoginTest", "PASS", 2.456);
System.out.println(report);
// String.join — concatenate with a delimiter
String csv = String.join(",", "Chrome", "Firefox", "Safari");
System.out.println(csv); // Chrome,Firefox,Safari
// Join an array
String[] tags = {"smoke", "regression", "critical"};
String tagString = String.join(" | ", tags);
System.out.println(tagString); // smoke | regression | critical
}
}public class RealExtractions {
public static void main(String[] args) {
// Extract order number from confirmation text
String confirmation = "Your order #ORD-12345 has been placed successfully";
int start = confirmation.indexOf("#") + 1;
int end = confirmation.indexOf(" ", start);
String orderNumber = confirmation.substring(start, end);
System.out.println("Order: " + orderNumber); // ORD-12345
// Extract all numbers from a mixed string
String text = "Page 3 of 25 (247 results)";
String[] numbers = text.replaceAll("[^0-9 ]", "").trim().split("\\s+");
System.out.println("Current page: " + numbers[0]); // 3
System.out.println("Total pages: " + numbers[1]); // 25
System.out.println("Total results: " + numbers[2]); // 247
// Clean element text for comparison
String elementText = " \n Welcome, John! \n ";
String cleaned = elementText.trim().replaceAll("\\s+", " ");
System.out.println("\"" + cleaned + "\""); // "Welcome, John!"
// URL parameter extraction
String url = "https://example.com/search?query=laptop&page=2&sort=price";
String queryString = url.substring(url.indexOf("?") + 1);
String[] params = queryString.split("&");
for (String param : params) {
String[] kv = param.split("=");
System.out.println(kv[0] + " → " + kv[1]);
}
}
}Order: ORD-12345
Current page: 3
Total pages: 25
Total results: 247
"Welcome, John!"
query → laptop
page → 2
sort → priceQ: What is the difference between String, StringBuilder, and StringBuffer?
A: String is immutable — every modification creates a new object. StringBuilder is mutable and faster for repeated modifications — use it when building strings in loops. StringBuffer is like StringBuilder but thread-safe (synchronized methods). In test automation, use String for normal operations and StringBuilder when concatenating inside loops. StringBuffer is rarely needed since most test code is single-threaded.
Exercise 1: Write a method that validates a password: at least 8 chars, at least one uppercase, one lowercase, one digit, and one special character. Return true/false.
Exercise 2: Given a URL like "https://shop.example.com/products/laptop-123", extract the product slug ("laptop-123") and the domain ("shop.example.com").
Exercise 3: Write a method that takes a sentence and returns it in title case — first letter of each word capitalized, rest lowercase. "hello WORLD from JAVA" → "Hello World From Java".
Answer all 10 questions, then submit to see your score.
1. What is the default value of elements in a new int[5]?
2. What does Arrays.toString(arr) return for int[] arr = {1, 2, 3}?
3. Which method adds an element to an ArrayList?
4. What does HashMap.getOrDefault("key", "N/A") return if "key" does not exist?
5. Which block always executes whether or not an exception occurs?
6. What type of exception is NullPointerException?
7. What does "hello".matches("\\d+") return?
8. What happens when you put a duplicate key in a HashMap?
9. Can an ArrayList hold primitive int values directly?
10. What is the difference between throw and throws?