📜  switch case java with char - Java (1)

📅  最后修改于: 2023-12-03 14:47:48.604000             🧑  作者: Mango

Switch case in Java with char

Switch case is a control flow statement in Java that allows you to select one of many possible code blocks to be executed based on the value of a variable or expression. It provides a convenient way to handle multiple conditions in a clean and concise manner.

In Java, switch case can be used with a char variable or expression to perform different actions based on the value of that variable or expression. The char data type represents a single 16-bit Unicode character and can store any character from the Unicode character set.

Here is an example that demonstrates the usage of switch case with char in Java:

public class CharSwitchExample {
    public static void main(String[] args) {
        char grade = 'A';

        switch (grade) {
            case 'A':
                System.out.println("Excellent!");
                break;
            case 'B':
                System.out.println("Good job!");
                break;
            case 'C':
                System.out.println("Fair enough.");
                break;
            case 'D':
                System.out.println("Needs improvement.");
                break;
            case 'F':
                System.out.println("Fail.");
                break;
            default:
                System.out.println("Invalid grade.");
        }
    }
}

In this example, we have a char variable named grade initialized with the value 'A'. The switch statement checks the value of grade and executes the corresponding code block based on the matching case. In this case, the output will be "Excellent!".

If none of the cases match the value of grade, the code block associated with the default label will be executed. In this example, if the value of grade is not 'A', 'B', 'C', 'D' or 'F', the output will be "Invalid grade.".

It's important to note that the value used in each case label must be a compile-time constant, which means it should be a literal or a final/static variable.

Switch case with char in Java provides an efficient way to handle multiple conditions and can be a good alternative to using multiple if-else statements when dealing with char variables or expressions.