12

Java switch Expression

 5 years ago
source link: https://www.tuicool.com/articles/RBVFvqi
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

A Java switch statement works a bit like an if statement, except it can choose between more than two blocks of code to execute. Here is a simple example:

int amount = 9;

<b>switch</b>(amount) {
    <b>case</b>     0 : System.out.println("amount is  0"); break;
    <b>case</b>     5 : System.out.println("amount is  5"); break;
    <b>case</b>    10 : System.out.println("amount is 10"); break;
    <b>default</b>    : System.out.println("amount is something else");
}

This example first creates a variable named amount and assigns the value 9 to it.

Second, the example "switches" on the value of the amount variable. Inside the switch statement are 3 case statements and a default statement.

Each case statement compares the value of the amount variable with a constant value. If the amount variable value is equal to that constant value, the code after the colon (:) is executed. Notice the break keyword after each statement. If no break keyword was place here, the execution could continue down the rest of the case statements until a break is met, or the end of the switch statement is reached. The break keyword makes execution jump out of the switch statement.

The default statement is executed if no case statement matched the value of the amount variable. The default statement could also be executed if the case statements before it did not have a break command in the end. You don't need a default statement. It is optional.

Switch on byte, short, char, int, String, or enum's

As you have seen, the switch statement switches on a variable. Before Java 7 this variable has to be numeric and must be either a byte , short , char or int . From Java 7 the variable can also be a String It is also possible switch on aJava enum variable.

Multiple case statements for same operation

In case you want the same operation executed for multiple case statements, you write it like this:

char key = '\t'

switch(amount) {
    case     ' '  :
    case     '\t' : System.out.println("white space char"); break;

    default       : System.out.println("amount is something else");
}

Notice how the first case statement does not have any operation after the colon. The result of this is, that execution just "drops" down to the operation of the next case statement ( and the next etc.) until a break is met. The next break statement is after the second case statement. That means, that for both the first and second case statement, the same operation is executed - that of the second case statement.

Java switch Expressions

Java 12 added the switch expression as experimental feature. A Java switch expression a switch statement which can return a value. Thus, it can be evaluated as an expression, just like other Java expressions (which are also evaluated to a value). In this section I will show you how the Java switch expressions of Java 12 works.

Here is first a Java switch expression example:

int  digitInDecimal = 12;
char digitInHex     =
    switch(digitInDecimal){
        case  0 -> '0';
        case  1 -> '1';
        case  2 -> '2';
        case  3 -> '3';
        case  4 -> '4';
        case  5 -> '5';
        case  6 -> '6';
        case  7 -> '7';
        case  8 -> '8';
        case  9 -> '9';
        case 10 -> 'A';
        case 11 -> 'B';
        case 12 -> 'C';
        case 13 -> 'D';
        case 14 -> 'E';
        case 15 -> 'F';

        default -> '?';
    };

System.out.println(digitInHex);

This Java switch expression example converts a value between 0 and 15 to a hexadecimal digit character.

Notice how the colon ( : ) after each case statement has been replaced with a -> operator. This operator is used inside of switch expressions to signal to the Java compiler that this case statement selects a return value for the switch expression, rather than selecting a block of code to execute.

Notice also, that the case statements have no break keyword after them. Since the value selected with the -> operator is interpreted as the return value of the switch expression, the break after each statement is implicit (unnecessary actually). You can also think of the -> as a return statement which returns a value from the switch expression, and thus breaks the execution of the switch expression.

Finally, notice how the digitInHex variable is assigned the return value of the switch expression. This is how you capture the output of a Java switch expression. You could also have returned its value as a return value from a method, like this:

public char toHexDigit(int digitInDecimal) {

    return
    switch(digitInDecimal){
        case  0 -> '0';
        case  1 -> '1';
        case  2 -> '2';
        case  3 -> '3';
        case  4 -> '4';
        case  5 -> '5';
        case  6 -> '6';
        case  7 -> '7';
        case  8 -> '8';
        case  9 -> '9';
        case 10 -> 'A';
        case 11 -> 'B';
        case 12 -> 'C';
        case 13 -> 'D';
        case 14 -> 'E';
        case 15 -> 'F';

        default -> '?';
    };

}

The Java switch expression also works withJava String values. Here is a Java switch expression example using Strings to switch on:

String token = "123";

int tokenType = switch(token) {
    case "123" -> 0;
    case "abc" -> 1;
    default -> -1;
};

This example resolves a token type (integer value) based on the values of a String token.

switch Expression Use Cases

The Java switch expressions are useful in use cases where you need to obtain a value based on another value. For instance, when converting between number values and characters, as shown in the example above.

Java switch expressions are also useful when parsing characters into values, or String tokens into integer token types. In general, whenever you need to resolve one value to another.


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK