Complete Programming Guide for QA/SDET Engineers
Conditional statements allow your program to make decisions and execute different code based on conditions. They are fundamental for test logic, validations, and handling different test scenarios.
The most common conditional statement. Executes code blocks based on boolean conditions evaluated from top to bottom.
public class IfElseExample { public static void main(String[] args) { int testsPassed = 45; int totalTests = 50; double passRate = (testsPassed * 100.0) / totalTests; if (passRate >= 90) { System.out.println("Excellent! Grade: A"); } else if (passRate >= 80) { System.out.println("Great! Grade: B"); } else if (passRate >= 70) { System.out.println("Good! Grade: C"); } else if (passRate >= 60) { System.out.println("Pass! Grade: D"); } else { System.out.println("Fail! Grade: F"); } } }
public class SwitchExample { public static void main(String[] args) { String browser = "chrome"; switch (browser.toLowerCase()) { case "chrome": System.out.println("Launching Chrome browser"); break; case "firefox": System.out.println("Launching Firefox browser"); break; case "edge": System.out.println("Launching Edge browser"); break; case "safari": System.out.println("Launching Safari browser"); break; default: System.out.println("Unknown browser"); } } }
public class NestedIfExample { public static void main(String[] args) { boolean isLoggedIn = true; boolean hasPermission = true; String userRole = "admin"; if (isLoggedIn) { if (hasPermission) { if (userRole.equals("admin")) { System.out.println("✓ Full access granted"); } else { System.out.println("✓ Limited access granted"); } } else { System.out.println("✗ Access denied - No permission"); } } else { System.out.println("✗ Please log in first"); } } }
Create a program that determines the grade based on score:
Loops allow you to execute code repeatedly. Essential for iterating through test data, running multiple test cases, and automating repetitive tasks.
Best for iterating a known number of times. Syntax:
for (initialization; condition; increment)
public class ForLoopExample { public static void main(String[] args) { // Basic for loop for (int i = 1; i <= 5; i++) { System.out.println("Test case " + i + ": Executed"); } // Counting down for (int i = 5; i >= 1; i--) { System.out.println("Countdown: " + i); } // Increment by 2 for (int i = 0; i <= 10; i += 2) { System.out.println("Even number: " + i); } } }
public class WhileLoopExample { public static void main(String[] args) { int retryCount = 0; int maxRetries = 3; boolean testPassed = false; while (retryCount < maxRetries && !testPassed) { retryCount++; System.out.println("Attempt " + retryCount + ": Running test..."); // Simulate test passing on 3rd attempt if (retryCount == 3) { testPassed = true; System.out.println("✓ Test passed!"); } } if (!testPassed) { System.out.println("✗ Test failed after " + maxRetries + " attempts"); } } }
public class DoWhileExample { public static void main(String[] args) { int page = 1; int totalPages = 5; // Executes at least once, then checks condition do { System.out.println("Scraping page " + page); page++; } while (page <= totalPages); } }
public class BreakContinueExample { public static void main(String[] args) { // Break - exit loop entirely for (int i = 1; i <= 10; i++) { if (i == 5) { System.out.println("Critical error at test " + i); break; // Stop all tests } System.out.println("Running test " + i); } System.out.println("\n---\n"); // Continue - skip current iteration for (int i = 1; i <= 10; i++) { if (i % 2 == 0) { continue; // Skip even numbers } System.out.println("Test " + i + ": Odd number"); } } }
Write a program to calculate factorial of 5 using a loop:
Arrays are fixed-size containers that store multiple values of the same type. Essential for managing test data, storing test results, and handling collections of web elements.
Key Points:
public class ArrayExample { public static void main(String[] args) { // Method 1: Declare then initialize int[] scores; scores = new int[5]; scores[0] = 85; scores[1] = 90; // Method 2: Declare and initialize together String[] browsers = new String[3]; // Method 3: Initialize with values String[] testStatus = {"Pass", "Fail", "Skip", "Pass"}; // Access elements System.out.println("First status: " + testStatus[0]); System.out.println("Array length: " + testStatus.length); // Iterate through array for (int i = 0; i < testStatus.length; i++) { System.out.println("Test " + (i+1) + ": " + testStatus[i]); } } }
public class ForEachExample { public static void main(String[] args) { String[] browsers = {"Chrome", "Firefox", "Safari", "Edge"}; // Enhanced for loop for (String browser : browsers) { System.out.println("Testing on: " + browser); } // With numbers int[] scores = {85, 92, 78, 95, 88}; int sum = 0; for (int score : scores) { sum += score; } double average = (double) sum / scores.length; System.out.println("Average score: " + average); } }
public class MultiDimensionalArray { public static void main(String[] args) { // 2D array - test results for 3 suites, 4 tests each int[][] testResults = { {1, 1, 0, 1}, // Suite 1 (1=pass, 0=fail) {1, 1, 1, 1}, // Suite 2 {1, 0, 1, 1} // Suite 3 }; // Iterate through 2D array for (int i = 0; i < testResults.length; i++) { System.out.println("Suite " + (i+1) + ":"); for (int j = 0; j < testResults[i].length; j++) { String status = testResults[i][j] == 1 ? "PASS" : "FAIL"; System.out.println(" Test " + (j+1) + ": " + status); } } } }
import java.util.Arrays; public class ArrayMethods { public static void main(String[] args) { int[] numbers = {5, 2, 8, 1, 9}; // Sort array Arrays.sort(numbers); System.out.println("Sorted: " + Arrays.toString(numbers)); // Binary search (array must be sorted) int index = Arrays.binarySearch(numbers, 8); System.out.println("Index of 8: " + index); // Fill array int[] filled = new int[5]; Arrays.fill(filled, 10); System.out.println("Filled: " + Arrays.toString(filled)); // Copy array int[] copy = Arrays.copyOf(numbers, numbers.length); System.out.println("Copy: " + Arrays.toString(copy)); } }
Find the maximum and minimum values in an array:
Strings are sequences of characters and one of the most commonly used data types in test automation. Understanding String manipulation is crucial for handling test data, assertions, and dynamic content.
Key Concept: Strings are immutable - once created, they cannot be changed. Any modification creates a new String object.
| Feature | String | StringBuilder |
|---|---|---|
| Mutability | Immutable | Mutable |
| Performance | Slower for concatenation | Faster for concatenation |
| Use Case | Few modifications | Many modifications (loops) |
| Thread Safety | Thread-safe | Not thread-safe |
StringBuilder when building strings in loops
(e.g., generating test reports with many test results). Use String for simple
concatenations.
public class StringBasics { public static void main(String[] args) { // String creation String str1 = "Hello"; String str2 = new String("Hello"); // String concatenation String firstName = "John"; String lastName = "Doe"; String fullName = firstName + " " + lastName; System.out.println(fullName); // String length System.out.println("Length: " + fullName.length()); // Character at index System.out.println("First char: " + fullName.charAt(0)); } }
public class StringMethods { public static void main(String[] args) { String text = " Test Automation with Java "; // Trim whitespace System.out.println("Trimmed: '" + text.trim() + "'"); // Case conversion System.out.println("Upper: " + text.toUpperCase()); System.out.println("Lower: " + text.toLowerCase()); // Substring System.out.println("Substring: " + text.substring(2, 6)); // Replace System.out.println("Replace: " + text.replace("Java", "Python")); // Contains System.out.println("Contains 'Test': " + text.contains("Test")); // Starts/Ends with System.out.println("Starts with ' Test': " + text.startsWith(" Test")); // Split String[] words = text.trim().split(" "); System.out.println("Words: " + java.util.Arrays.toString(words)); } }
public class StringComparison { public static void main(String[] args) { String str1 = "Test"; String str2 = "Test"; String str3 = new String("Test"); String str4 = "test"; // == compares references System.out.println(str1 == str2); // true System.out.println(str1 == str3); // false // equals() compares content System.out.println(str1.equals(str3)); // true System.out.println(str1.equals(str4)); // false // equalsIgnoreCase() System.out.println(str1.equalsIgnoreCase(str4)); // true } }
public class StringBuilderExample { public static void main(String[] args) { // StringBuilder is mutable and efficient StringBuilder sb = new StringBuilder("Test"); sb.append(" Automation"); sb.append(" Framework"); System.out.println(sb.toString()); sb.insert(0, "Selenium "); System.out.println(sb); sb.reverse(); System.out.println(sb); } }
Count the number of vowels in a string: