JAVA Syllabus
QUESTIONS & ANSWERS

Explain all types of control statements in java?

In Java, control statements are used to control the flow of execution of a program. There are three types of control statements in Java: selection statements, iteration statements, and jump statements.

  1. Selection Statements: Selection statements allow a program to execute different blocks of code based on different conditions. There are two types of selection statements in Java:
    if-else statement: This statement executes a block of code if a specified condition is true, and another block of code if the condition is false. Syntax:
    if (condition) {
      // code to execute if condition is true
    } else {
      // code to execute if condition is false
    }
    
    switch statement: This statement allows a program to execute different blocks of code based on the value of a variable. Syntax:
    switch (expression) {
      case value1:
        // code to execute if expression == value1
        break;
      case value2:
        // code to execute if expression == value2
        break;
      ...
      default:
        // code to execute if none of the cases match
        break;
    }
    
  2. Iteration Statements: Iteration statements are used to execute a block of code repeatedly. There are three types of iteration statements in Java:
    for loop: This statement executes a block of code for a specified number of times. Syntax:
    for (initialization; condition; update) {
      // code to execute repeatedly
    }
    

    while loop: This statement executes a block of code as long as a specified condition is true. Syntax:

    while (condition) {
      // code to execute repeatedly
    }
    

    do-while loop: This statement executes a block of code at least once, and then repeats the block as long as a specified condition is true. Syntax:

    do {
      // code to execute repeatedly
    } while (condition);
    

    for-each loop: In Java, a for-each loop (also known as an enhanced for loop) is a convenient way to iterate over elements in a collection or an array. It is especially useful when you want to process all the elements in a collection or array in a sequential order.

    for (int number : numbers) {
        System.out.println(number);
    }
    
  3. Jump Statements: Jump statements are used to transfer control from one part of a program to another part. There are three types of jump statements in Java:
    break statement: This statement is used to terminate the execution of a loop or switch statement. Syntax:
    break;
    

    continue statement: This statement is used to skip the current iteration of a loop and move to the next iteration. Syntax:

    continue;
    

    return statement: This statement is used to terminate the execution of a method and return a value to the calling method. Syntax:

    return value;
    
04/03/2023, 11:32 am Read : 96 times