switch case java with char

htt‮p‬s://www.lautturi.com
switch case java with char

In Java, you can use a switch statement to execute a block of code based on the value of a char variable.

Here's an example of how to use a switch statement with a char variable:

char c = 'A';

switch (c) {
    case 'A':
        System.out.println("A was chosen");
        break;
    case 'B':
        System.out.println("B was chosen");
        break;
    case 'C':
        System.out.println("C was chosen");
        break;
    default:
        System.out.println("None of the above were chosen");
        break;
}

In this example, the switch statement compares the value of the c variable with the cases specified in the switch statement. If the value of c is 'A', the code in the first case will be executed. If the value of c is 'B', the code in the second case will be executed, and so on. If the value of c does not match any of the cases, the code in the default case will be executed.

In each case, the break statement is used to exit the switch statement and prevent the code in the following cases from being executed. If you omit the break statement, the code in all the following cases will be executed as well.

You can find more information about the switch statement and how to use it in Java in the Java documentation.

Created Time:2017-10-17 20:18:56  Author:lautturi