QA Interview Handbook
  • ๐Ÿ Home Page
  • About Testing
    • ๐Ÿ’–Qualities of A Great Tester
  • Manual Testing
    • ๐Ÿ’กOverview
      • โœ‹Demand for Software Testing
      • ๐Ÿ˜„Tester's Role in Manual Testing
      • 7๏ธTesting Principles
      • ๐ŸšจV & V
      • โ”Interview Questions
    • โ™ป๏ธSDLC
      • ๐Ÿ“’Phase 1: Planning
      • ๐Ÿ”Phase 2: Requirement Analysis
      • ๐Ÿ‘”Phase 3: Design
      • โ›‘๏ธPhase 4: Development
      • ๐ŸงชPhase 5: Testing
      • ๐ŸššPhase 6: Deployment
      • ๐Ÿ–ฑ๏ธPhase 7: Maintenance
      • โš”๏ธCommon Challenges
      • โ”Interview Questions
    • ๐ŸŒ€STLC
    • ๐ŸŒŠWaterfall
    • โœณ๏ธAgile
      • ๐Ÿ˜Tester's Role in Scrum
    • ๐Ÿ”ขTypes
      • โฌœWhite Box Testing
      • โฌ›Black Box Testing
        • ๐Ÿ”ฐTechniques Used in Black Box Testing
        • ๐Ÿš˜Functional Testing
          • 1๏ธโƒฃUnit Testing
          • 2๏ธโƒฃIntegration Testing
            • ๐Ÿ”ฐTechniques Used in Integration Testing
          • 3๏ธโƒฃSystem Testing
            • ๐Ÿ“ผTypes of System Testing
            • ๐ŸŒŠPhases of System Testing
            • ๐ŸŒ€Regression Testing
            • ๐ŸŒซ๏ธSmoke Testing
          • 4๏ธโƒฃAcceptance Testing
            • โš™๏ธUser Acceptance Testing
            • ๐Ÿ…ฐ๏ธAlpha Testing
            • ๐Ÿ…ฑ๏ธBeta Testing
        • ๐Ÿ•ณ๏ธNon Functional Testing
      • ๐Ÿ“‘Grey Box Testing
    • ๐Ÿช„User Story
      • โบ๏ธSample User Stories
    • ๐Ÿ““Test Cases
      • โบ๏ธSample Test Cases
      • โ”Interview Questions
    • โœ–๏ธDefect Life Cycle
      • โ˜ฃ๏ธPriority + Severity
      • โบ๏ธSample Defect Reports
      • โ”Interview Questions
      • ๐Ÿ›Buggy Questions
    • ๐ŸŒAtlassian JIRA
      • ๐ŸžJIRA Issues
      • โ”Interview Questions
    • โ”Interview Questions
  • Accessibility Testing
    • ๐Ÿ’กOverview
    • ๐Ÿค“Tester's Role in Accessibility Testing
    • ๐Ÿ“šWCAG Principles
      • ๐Ÿ‘๏ธPerceivable
      • ๐ŸนOperable
      • ๐Ÿง Understandable
      • ๐Ÿค–Robust
    • ๐Ÿ”งAxe DevTools
      • โ”Interview Questions
    • ๐Ÿ““Test Cases
    • โ”Interview Questions
  • API Testing
    • ๐Ÿ’กOverview
    • ๐Ÿ˜€Tester's Role in API Testing
    • ๐ŸŠHTTP Methods & CRUD
      • ๐Ÿ‚HTTP Status Codes
    • ๐ŸAPI Tools
      • ๐ŸŸ Postman
        • โ˜„๏ธSending your first API request
        • ๐Ÿ”ฌHTTP Requests with Java
        • ๐ŸŽฒGitHub Sample
        • โ”Interview Questions
      • โ›‘๏ธREST Assured
        • ๐ŸŽ‡Dependency
        • โ”Interview Questions
    • ๐Ÿ““Test Cases
    • ๐ŸฆงAPI Cheatsheet
    • โ”Interview Questions
  • Database Testing
    • ๐Ÿ’กOverview
    • ๐Ÿ˜†Tester's Role in Database Testing
    • ๐Ÿ”ตSQL
      • โ›“๏ธConstraints
      • ๐Ÿ›ข๏ธReferencing a Column
      • ๐Ÿ”ผDDL Commands
      • ๐Ÿ”ผDML Commands
        • ๐Ÿ–Œ๏ธOperators
        • ๐Ÿ› ๏ธFunctions
          • โฏ๏ธAggregate Functions
        • ๐ŸŽ…Clauses
          • โซJoin Clauses
          • ๐Ÿ”ตFilter Clauses
          • โฌSet Operations
      • ๐ŸƒWildcard Character
      • โ”Interview Questions
    • ๐Ÿ““Test Cases
    • ๐ŸงคSQL Practice Sites
    • ๐ŸซSQL Cheatsheet
    • โ”Interview Questions
  • Java
    • โ›ฉ๏ธIntroduction
    • ๐Ÿ˜„Tester's Reason to Learn Java
    • โ“‚๏ธMain Method
      • โ”Interview Questions
    • ๐Ÿ“Variables & Types
      • ๐ŸชขSpecial Types
    • ๐ŸฅModifiers
    • ๐Ÿ…พ๏ธOperators
    • ๐ŸชกString
      • ๐ŸฉบString Methods
        • String Method Problems
      • ๐ŸšจDelimiter
      • โ”Interview Questions
    • ๐Ÿ–‡๏ธConditionals
      • ๐Ÿ’ŽCommon If Statements
      • ๐Ÿ’ŽCommon Ternary Operator Statements
    • โ“‚๏ธMath Class
    • ๐ŸŒŠLoops
      • ๐Ÿ’ŽCommon Loop Examples
      • ๐Ÿ”ƒNested For Loops
    • ๐ŸผOOPS
      • ๐Ÿ›๏ธClasses and Objects
        • โ”Interview Questions
      • ๐ŸŽƒConstructor
        • โšกStatic
          • โ”Interview Questions
        • ๐Ÿ“This() & Super()
          • โ”Interview Questions
        • ๐Ÿ€Finalization
      • ๐Ÿ”“Encapsulation
      • ๐ŸฅInheritance
      • ๐Ÿฆ‹Polymorphism
      • ๐Ÿ•ธ๏ธAbstraction
    • ๐ŸฎJava Practice Sites
    • โ˜‘๏ธData Structures + Algorithms
      • ๐Ÿ…พ๏ธBig O
      • โ˜‘๏ธData Structures
        • ๐Ÿ”ธArray
        • ๐Ÿ”ณArray Problems
        • Page
      • ๐ŸชŸSliding Window Technique
        • ๐ŸชŸSliding Window Problems
        • ๐ŸฅLeetCode #53
        • ๐ŸฅLeetCode #209
    • โ”Interview Questions
  • Automation Testing
    • ๐ŸšฐFlow
      • ๐Ÿ’กOverview
      • ๐ŸคฉTester's Role in Automation Testing
      • ๐Ÿ€Selenium
        • ๐Ÿ•ธ๏ธSelenium WebDriver
          • ๐Ÿ•ท๏ธWebDriver Commands
            • ๐ŸŒWebElement
              • ๐Ÿ”†HTML Tags
              • ๐Ÿ”ฌFind Element(s)
              • ๐ŸฆŽLocators
                • โŒXpath
                • ๐ŸฐCSS Selector
                • ๐Ÿ“€DOM
                • ๐Ÿ Quick Reference for XPath + CSS
            • โœ‹Waits
            • Browser Management
            • ๐ŸŽ๏ธNavigation
            • Alerts
          • ๐Ÿท๏ธAdvanced User Interactions
            • ๐Ÿ—ฏ๏ธAction vs. Actions
            • ๐Ÿ’งDrop Down
            • โœ…Check Box
            • ๐Ÿ–‡๏ธForms
          • โš ๏ธExceptions
        • ๐ŸOOPS + Selenium
        • ๐ŸšขFrameworks
          • โš“Module Based Framework
          • ๐ŸŽนKeyword Driven Framework
          • ๐ŸŽ‹Data Driven Framework
          • ๐ŸŒบHybrid Framework
          • ๐ŸŒดLog4j
          • ๐Ÿ“„Page Object Model
        • ๐ŸงชTesting Frameworks
          • ๐Ÿ’กTestNG
          • ๐Ÿ‰‘JUnit
          • ๐Ÿฅ’BDD
            • ๐Ÿฅ’Cucumber
        • ๐ŸŒ‰Selenium Grid
          • โœ–๏ธDesired Capabilities
        • โ”Interview Questions
      • ๐Ÿ”„API Testing with Selenium
      • โชDatabase Testing with Selenium
      • โ“‚๏ธMaven
      • ๐Ÿ™Git
        • โ”Interview Questions
      • ๐Ÿ•ต๏ธโ€โ™‚๏ธJenkins
        • โ”Interview Questions
      • ๐ŸณDocker
        • โ”Interview Questions
      • ๐Ÿ“™AWS
        • โ”Interview Questions
  • Behavioral
    • ๐Ÿ“ฃMixed Interview Questions
    • โญSTAR Method
      • ๐ŸŒŸSample Responses
Powered by GitBook
On this page
  • For Loop
  • While Loop
  • For-Each Loop
  • Switch Statement

Was this helpful?

  1. Java
  2. Loops

Common Loop Examples

For Loop

  1. Print numbers from 1 to 10 using a for loop.

for (int i = 1; i <= 10; i++) {
    System.out.println(i);
}
  1. Print even numbers from 1 to 20 using a for loop.

for (int i = 2; i <= 20; i += 2) {
    System.out.println(i);
}
  1. Print odd numbers from 1 to 20 using a for loop.

for (int i = 1; i <= 20; i += 2) {
    System.out.println(i);
}
  1. Calculate the sum of numbers from 1 to 100 using a for loop.

int sum = 0;
for (int i = 1; i <= 100; i++) {
    sum += i;
}
System.out.println("Sum: " + sum);
  1. Print the multiplication table of a given number using a for loop.

int number = 5;
for (int i = 1; i <= 10; i++) {
    System.out.println(number + " x " + i + " = " + (number * i));
}
  1. Print the Fibonacci series up to a given number using a for loop.

int n = 10;
int first = 0;
int second = 1;
System.out.print(first + " " + second + " ");
for (int i = 2; i < n; i++) {
    int next = first + second;
    System.out.print(next + " ");
    first = second;
    second = next;
}
  1. Find the factorial of a given number using a for loop.

int number = 5;
int factorial = 1;
for (int i = 1; i <= number; i++) {
    factorial *= i;
}
System.out.println("Factorial: " + factorial);
  1. Print the reverse of a given string using a for loop.

String str = "Hello World";
for (int i = str.length() - 1; i >= 0; i--) {
    System.out.print(str.charAt(i));
}
  1. Check if a given number is prime using a for loop.

int number = 17;
boolean isPrime = true;
for (int i = 2; i <= Math.sqrt(number); i++) {
    if (number % i == 0) {
        isPrime = false;
        break;
    }
}
System.out.println("Is Prime: " + isPrime);
  1. Count the number of vowels in a given string using a for loop.

String str = "Hello World";
int vowelCount = 0;
for (int i = 0; i < str.length(); i++) {
    char ch = Character.toLowerCase(str.charAt(i));
    if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u') {
        vowelCount++;
    }
}
System.out.println("Vowel Count: " + vowelCount);

While Loop

  1. Print numbers from 1 to 10 using a while loop.

int i = 1;
while (i <= 10) {
    System.out.println(i);
    i++;
}
  1. Print even numbers from 1 to 20 using a while loop.

int i = 2;
while (i <= 20) {
    System.out.println(i);
    i += 2;
}
  1. Print odd numbers from 1 to 20 using a while loop.

int i = 1;
while (i <= 20) {
    System.out.println(i);
    i += 2;
}
  1. Calculate the sum of numbers from 1 to 100 using a while loop.

int i = 1;
int sum = 0;
while (i <= 100) {
    sum += i;
    i++;
}
System.out.println("Sum: " + sum);
  1. Print the multiplication table of a given number using a while loop.

int number = 5;
int i = 1;
while (i <= 10) {
    System.out.println(number + " x " + i + " = " + (number * i));
    i++;
}
  1. Print the Fibonacci series up to a given number using a while loop.

int n = 10;
int first = 0;
int second = 1;
System.out.print(first + " " + second + " ");
int i = 2;
while (i < n) {
    int next = first + second;
    System.out.print(next + " ");
    first = second;
    second = next;
    i++;
}
  1. Find the factorial of a given number using a while loop.

int number = 5;
int factorial = 1;
int i = 1;
while (i <= number) {
    factorial *= i;
    i++;
}
System.out.println("Factorial: " + factorial);
  1. Print the reverse of a given string using a while loop.

String str = "Hello World";
int i = str.length() - 1;
while (i >= 0) {
    System.out.print(str.charAt(i));
    i--;
}
  1. Check if a given number is prime using a while loop.

int number = 17;
boolean isPrime = true;
int i = 2;
while (i <= Math.sqrt(number)) {
    if (number % i == 0) {
        isPrime = false;
        break;
    }
    i++;
}
System.out.println("Is Prime: " + isPrime);
  1. Count the number of vowels in a given string using a while loop.

String str = "Hello World";
int vowelCount = 0;
int i = 0;
while (i < str.length()) {
    char ch = Character.toLowerCase(str.charAt(i));
    if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u') {
        vowelCount++;
    }
    i++;
}
System.out.println("Vowel Count: " + vowelCount);

For-Each Loop

The foreach loop is used to iterate over elements of an array or a collection without using an index variable. The syntax for a foreach loop is as follows:

for (type var : array/collection) {
    // statements to be executed
}

Here are some examples of using foreach loops in Java:

  1. Print elements of an array using a foreach loop.

int[] numbers = {1, 2, 3, 4, 5};
for (int num : numbers) {
    System.out.println(num);
}
  1. Print elements of a list using a foreach loop.

List<String> names = new ArrayList<>();
names.add("Alice");
names.add("Bob");
names.add("Charlie");
for (String name : names) {
    System.out.println(name);
}
  1. Calculate the sum of elements in an array using a foreach loop.

int[] numbers = {1, 2, 3, 4, 5};
int sum = 0;
for (int num : numbers) {
    sum += num;
}
System.out.println("Sum: " + sum);
  1. Print the multiplication table of a given number using a foreach loop.

int number = 5;
int[] multiples = new int[10];
for (int i = 0; i < multiples.length; i++) {
    multiples[i] = number * (i + 1);
}
for (int multiple : multiples) {
    System.out.println(multiple);
}
  1. Print the Fibonacci series up to a given number using a foreach loop.

int n = 10;
List<Integer> fib = new ArrayList<>();
fib.add(0);
fib.add(1);
for (int i = 2; i < n; i++) {
    int next = fib.get(i - 1) + fib.get(i - 2);
    fib.add(next);
}
for (int num : fib) {
    System.out.print(num + " ");
}

The time and space complexity of foreach loops in Java are the same as for loops, which depend on the number of iterations and the size of the array or collection. The time complexity of a foreach loop is O(n), where n is the number of iterations. The space complexity of a foreach loop is O(1), as it only uses a fixed number of variables.

Switch Statement

The next important loop commonly used in interviews is the switch statement. The switch statement is used to perform different actions based on different conditions. It provides an alternative to using multiple if-else statements. The syntax for a switch statement is as follows:

switch (expression) {
    case value1:
        // statements to be executed if expression matches value1
        break;
    case value2:
        // statements to be executed if expression matches value2
        break;
    ...
    default:
        // statements to be executed if expression doesn't match any case
}

Here are some examples of using switch statements in Java:

  1. Print the name of the day based on the day number using a switch statement.

int day = 3;
String dayName;
switch (day) {
    case 1:
        dayName = "Monday";
        break;
    case 2:
        dayName = "Tuesday";
        break;
    case 3:
        dayName = "Wednesday";
        break;
    case 4:
        dayName = "Thursday";
        break;
    case 5:
        dayName = "Friday";
        break;
    case 6:
        dayName = "Saturday";
        break;
    case 7:
        dayName = "Sunday";
        break;
    default:
        dayName = "Invalid day";
}
System.out.println("Day: " + dayName);
  1. Calculate the number of days in a given month using a switch statement.

int month = 2;
int year = 2023;
int days;
switch (month) {
    case 1:
    case 3:
    case 5:
    case 7:
    case 8:
    case 10:
    case 12:
        days = 31;
        break;
    case 4:
    case 6:
    case 9:
    case 11:
        days = 30;
        break;
    case 2:
        if ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0) {
            days = 29;
        } else {
            days = 28;
        }
        break;
    default:
        days = -1;
}
System.out.println("Number of days: " + days);
  1. Perform different operations based on the operator using a switch statement.

int num1 = 10;
int num2 = 5;
char operator = '+';
int result;
switch (operator) {
    case '+':
        result = num1 + num2;
        break;
    case '-':
        result = num1 - num2;
        break;
    case '*':
        result = num1 * num2;
        break;
    case '/':
        result = num1 / num2;
        break;
    default:
        result = 0;
}
System.out.println("Result: " + result);

The time and space complexity of switch statements in Java are constant, O(1), as the execution time and memory usage do not depend on the number of cases. However, the efficiency of a switch statement can be impacted by the number of cases and the complexity of the statements within each case.

PreviousLoopsNextNested For Loops

Last updated 1 year ago

Was this helpful?

๐ŸŒŠ
๐Ÿ’Ž