☕ Java Fundamentals

Complete Programming Guide for QA/SDET Engineers

Part 2 of 4

🔀 Conditional Statements

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.

Types of Conditional Statements

  • if-else: Execute code based on true/false conditions
  • else if: Check multiple conditions in sequence
  • switch: Select one of many code blocks to execute
  • Ternary operator (?:): Shorthand for simple if-else
🎯 Conditional Statements in QA:
  • Test Validation: if (actualResult == expectedResult) → pass else → fail
  • Browser Selection: switch(browser) → launch appropriate driver
  • Environment Setup: if (env == "prod") → use prod URL else → use test URL
  • Error Handling: if (element.isDisplayed()) → click else → log error

If-Else Statement

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");
        }
    }
}

Switch Statement

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");
        }
    }
}

Nested If Statements

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");
        }
    }
}

Interactive Exercise: Grade Calculator

💻 Build a Grade Calculator

Create a program that determines the grade based on score:

🔄 Loops

Loops allow you to execute code repeatedly. Essential for iterating through test data, running multiple test cases, and automating repetitive tasks.

🎯 Loops in QA:
  • Data-Driven Testing: Loop through test data sets
  • Element Iteration: Process multiple web elements
  • Retry Logic: Retry failed operations with while loops
  • Batch Operations: Execute same test on multiple browsers

For Loop

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);
        }
    }
}

While Loop

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");
        }
    }
}

Do-While Loop

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);
    }
}

Break and Continue

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");
        }
    }
}

Interactive Exercise: Factorial

💻 Calculate Factorial

Write a program to calculate factorial of 5 using a loop:

💡 QA Use Cases:
  • For loop: Iterate through test data sets
  • While loop: Retry logic for flaky tests
  • Do-while: Ensure test runs at least once
  • Break: Stop on first critical failure
  • Continue: Skip disabled test cases

📚 Arrays

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.

🎯 Arrays in QA:
  • Test Data: Store multiple test credentials, URLs, or input values
  • Element Collections: Handle multiple web elements (buttons, links, rows)
  • Expected Results: Array of expected values for data-driven tests
  • Browser List: Array of browsers for cross-browser testing

Array Basics

Key Points:

  • Fixed size - cannot change after creation
  • Zero-indexed - first element is at index 0
  • Homogeneous - all elements must be same type
  • length property - returns number of elements

Array Declaration & Initialization

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]);
        }
    }
}

Enhanced For Loop (For-Each)

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);
    }
}

Multi-Dimensional Arrays

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);
            }
        }
    }
}

Array Methods (java.util.Arrays)

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));
    }
}

Interactive Exercise: Find Max & Min

💻 Array Statistics

Find the maximum and minimum values in an array:

📝 Strings

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.

🎯 Strings in QA:
  • Test Data: Build dynamic usernames, passwords, URLs
  • Assertions: Compare expected vs actual text from UI
  • Locators: Build dynamic XPath/CSS selectors
  • Reports: Generate test result messages

String Immutability

Key Concept: Strings are immutable - once created, they cannot be changed. Any modification creates a new String object.

String vs StringBuilder

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
💡 Best Practice: Use StringBuilder when building strings in loops (e.g., generating test reports with many test results). Use String for simple concatenations.

String Basics

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));
    }
}

String Methods

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));
    }
}

String Comparison

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
    }
}

StringBuilder

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);
    }
}

Interactive Exercise: Vowel Counter

💻 Count Vowels

Count the number of vowels in a string:

⚠️ Remember:
  • Strings are immutable - every modification creates a new String
  • Use StringBuilder for frequent modifications
  • Use .equals() to compare content, not ==
  • String indices start at 0