
Switch Statement
In a previous tutorial, we discussed the if...else conditional statement. Well, in this tutorial, we are done with looping and we are going to discuss again another type of conditional statement which is the switch statemment. This kind of statement is used when we have many conditions to choose from. Therefore, instead of using multiple if statements we do this by using a switch.
The switch Statement
Now, let's cover how the switch statement is written. Let's take a look at an abstract example of how to write it.
switch(variable)
{
case condition: code to do
break;
}
Notice that the
switch differs from the if in that the conditions are written inside the body and not between the paranthesis. We put the variable that we want to check in the paranthesis and in the body of the switch we use the case keyword to determine the condition and then do whatever operation we want to do. Finally, we always use a break after each case.
Now, let's take a look at a real Java code example.
public class Switch
{
public static void main(String args[])
{
int condition = 3;
switch(condition)
{
case 1: System.out.println("Java Judge");
break;
case 2: System.out.println("Java Editor");
break;
case 3: System.out.println("Java Tutorials");
break;
}
}
}
Output:
Java Tutorials
Always remember to break after every case. If you don't do so, all of the cases will be executed which may result in a wrong output.
Using default with switch
An extra concept when using switch is the default keyword. Simply, if all the cases are false, the default statement will execute. Take a look at the code below to check how default is used.
public class Default
{
public static void main(String args[])
{
char c = 'z';
switch(c)
{
case 'a': System.out.println("You entered a vowel");
break;
case 'i': System.out.println("A vowel");
break;
case 'o': System.out.println("A vowel");
break;
case 'e': System.out.println("A vowel");
break;
case 'u': System.out.println("A vowel");
break;
defaul: System.out.println("Not a vowel");
break;
}
}
}
Output:
Not a vowel
Congratulations
You now know how to use a switch statement. You are done with control statements now. You can move on to the next tutorial but first check the important notes below.
Important Notes
Never Forget to break
As mentioned above, always remember to break. Forgeting to break will not result in a compilation error but in wrong output. Try coding a switch without using break and see what happens.