
Autor: 16.01.2024
Java - Switch Case Statement
In this article, we will describe the Switch Case statement, which in some situations serves as an alternative to nested IF conditional statements. Let's get started!
The Simplest Switch Example
Depending on the situation, you can "switch" the code execution. Let's look at a specific example:
int number = 1;
switch(number) {
case 1:
System.out.println("one");
}
The switch statement tries to match the value of number to a case condition. If it can match the value, the corresponding code block will be executed. In our case, the output will be "one." Otherwise, the switch block will be skipped. Of course, this code is not very useful as it handles only one situation.
Expanding Our Example
There can be multiple case options. The example below shows this:
int number = 1;
switch(number) {
case 1:
System.out.println("one");
case 2:
System.out.println("two");
}
Choosing option 1 will output:
one
two
If the variable number has the value 2, the output will be:
two
To make sure that only the code in case 1 is executed for number=1, we use the break statement:
int number = 1;
switch(number) {
case 1:
System.out.println("one");
break;
case 2:
System.out.println("two");
break;
}
The break statement allows us to terminate the further processing of the switch. In our case, only option 1 will be executed.
Adding Handling for the Default Case
The default label comes in handy when there is no match in the switch case conditions. If none of the cases is matched, the code under the default label will be executed. Here's an example:
int number = 2;
switch(number) {
case 0:
System.out.print("zero ");
case 1:
System.out.print("one ");
break;
default:
System.out.println("default");
break;
}
The output will be:
default
So, we've covered the basic techniques of working with the Switch Case statement.
Handling Different Input Types
It's worth mentioning that the Switch statement can handle various input types. So far, we've checked numbers, but you can use other types of data. Look at the table below.
Type | Example |
char (Character) |
|
Enum |
|
String |
|
In practice, we often use this statement in combination with Enum types.