Switch statement in Java

Switch statement in Java is a statement used to check the value of a variable, which can have different values, depending on the value of this variable we can define a different set of statements.

For example, I have n variable that can be valued at 1,2,3. I want that in case the value of this n variable is 1, I will print the word “Khanh”, the value of 2 will print the word “Huong Dan Java”, the value of 3 will print “Lap Trinh Java “, using a switch statement, I will write the following code:

Here, we use the case label to handle for each different value of n variable. The declared value for each case must be COMPILE TIME CONSTANTS. This means that when compiling source code, the value of each case must be determined, no waiting until the program runs, execute to this switch code, the value of each case will then be determined.

To execute only the code for each value of n variable, we must use the break keyword so that after executing the code, our program will exit the switch statement.

As you can see, we also have a default label, this label is used to handle for cases where the value of this n variable is not in the case where the switch statement has been processed. In a switch statement, we may not need to declare the default label, if it is declared then it is not necessary to declare on a certain order!

The result when executing the above code will look like this:

Switch statement in Java

As you can see, because the value of n variable, in this case, is 1, the case for value 1 will be executed and print “Khanh”. After printing the text, to the break statement, our program will exit the switch statement.



Before Java 7, you can pass the variable of type char, byte, short, int or their wrapper Character, Byte, Short, Integer and Enum in a switch statement. From Java 7 onwards, the switch statement also supports String data type.

Result:

Switch statement in Java



You can pass into switch statement an expression as long as the return value of this expression is the allowable type of the switch statement.

Result:

Switch statement in Java

Add Comment