SWITCH STATEMENT IN JAVA WITH EXAMPLE

in Education11 months ago

SWITCH STATEMENT IN JAVA WITH EXAMPLE

The switch statement is used to replace a large number of nested if-else statement to make your code readable and usable. And each case in switch statement is accompanied by break statement which breaks the block when the case is compared with the input value. This simple program takes input from user which is usually string value and if the user enters the grade as A then it will print excellent and so on.

package Lesson1;

import java.util.Scanner;

public class SwitchClass {

    public static void main(String[] args) {
        Scanner user_input= new Scanner(System.in);
        System.out.println("Enter grade: ");
        String user_input_grade= user_input.nextLine();
        
        switch(user_input_grade) {
        
        case "A":
            System.out.println("Excellent");
            break;
        case "B":
            System.out.println("Very Good");
            break;
        case "C":
            System.out.println("Satisfactory");
            break;
        case "D":
            System.out.println("Poor");
            break;
        default:
            System.out.println("Very Poor");
            
        }
            
    }

}

A sample output of this code when executed

Screenshot_3.png

Sort:  

Thanks for publishing great tutorial on switch statement in JAVA. We are looking for people like you in our community.

Your post has been curated with @gitplait community account because this is the kind of publications we like to see in our community.

Join our Community on Hive and Chat with us on Discord.