Search Logic Blocks

Wednesday, January 15, 2020

Java: switch-case statement

Switch statements are also conditional statements. The body of the switch statement is known as a switch block. In switch-case statement, only one expression (a variable, simple or complex expression) is evaluated and executes different statements according to different values returned (cases). A statement in switch block can be labeled with one or more case or default labels.

switch(expression) {
  case value1: one or many statements;
                       break;
  case value2: one or many statements;
                       break;
  case value3: one or many statements;
                       break;
  case value4: one or many statements;
                       break;
  .......
  default: one or many statements;
}

The expression can be anything which returns the values of data types - byte, short, int, char,  String class or an enumeration. Values must be only the constant values. The statements are executed based on the returned values. When one case is satisfied, the statements are executed until there is a break statement. The break statement is compulsory to come out from the switch block, as the statements keep getting executed till a break statement or end of the block.

NOTE: We will discuss about strings and enumerations in later posts.

In below example, we ask the user to enter his grading in the exam and using switch-case block we print his range of marks he got in the exam. We are getting character as input, so we used System.i.read() method as we learnt in last post How to get input characters and strings from console. If the user enters anything else except 'A', 'B', 'C', 'D'; there is no case  so it will go to the default and prints the message - "Wrong grading!!"

Class SwitchCase (SwitchCase.java)
import java.io.IOException;

public class SwitchCase {
    public static void main(String args[]) throws IOException {
        System.out.println("Enter your grading ('A','B','C','D')");
        char grading = (char) System.in.read();
        switch(grading) {
            case 'A':
                System.out.println("You have A grading.");
                System.out.println("Your marks are between 75% and 100%.");
                break;
            case 'B':
                System.out.println("You have B grading.");
                System.out.println("Your marks are between 50% and 75%.");
                break;
            case 'C':
                System.out.println("You have C grading.");
                System.out.println("Your marks are between 25% and 50%.");
                break;
            case 'D':
                System.out.println("You have D grading.");
                System.out.println("Your marks are between 0% and 25%.");
                break;
            default: System.out.println("Wrong grading!!");
        }
    }
}

No comments: