In: Computer Science
Does break have to be used in each section of statements that follow a case in a switch statement? Detail your answer. *In Java*
It depends on the requirement.
Consider the below code:
int i=1;
switch(i) {
case 1:
System.out.println("First");
case 2:
System.out.println("Second");
case 3:
System.out.println("Third");
case 4:
System.out.println("Fourth");
default:
System.out.println("Default");
}
Output:
=====
First
Second
Third
Fourth
Default
In the above code, if we pass i=1, we will get output of all the cases including default as there is no break statement. This can be used in situations when we need all the case statements greater than a particular value. If we want to execute all the statements from case 3 on wards, then we can pass 3 as the value for i.
When we want execute only one case statement and we don't want other case statements to be executed then we can use break statement as shown below:
int i=1;
switch(i) {
case 1:
System.out.println("First");
break;
case 2:
System.out.println("Second");
break;
case 3:
System.out.println("Third");
break;
case 4:
System.out.println("Fourth");
break;
default:
System.out.println("Default");
}
Output:
======
First
In this code we have included break statements for all the cases. So when we pass 1 as the value of i then we get "First" in the output.