0
Can anyone tell me,please: in what cases do we need to write break after each case ad when we don't need to do that?
4 Answers
+ 2
means with no break it will continue to excecute the other lines after the case condition
+ 2
In some situations, you want to do specific actions for a couple of values but at the same time, if the value falls in a certain range, you want further testing and additional actions. Here is an example I can think of:
public class Program {
public static void main(String[] args) {
int result = 6;
switch(result) {
case 10:
System.out.println("Excellent");
break;
case 9:
System.out.println("Very Good");
break;
case 8:
System.out.println("Good");
break;
case 1:
System.out.println("very");
case 2:
System.out.println("very");
case 3:
System.out.println("very");
case 4:
System.out.println("very");
case 5:
System.out.println("very");
case 6:
System.out.println("very");
case 7:
System.out.println("bad");
}
}
}
If result is between 1 and 7, you'll get different number of "very" then "bad,"
+ 1
You need a break after each case to avoid fall-through.
+ 1
if u have no break then it will increase the runtime of the programme