java – Is it necessary to include "break" in the "default" of the "switch" control structure?

Question:

I've had this question for a while and I can't find any info about it.

Given the following switch:

switch (valor) {
  case 1:
       //código..
       break;
  case 2:
       //código..
       break;
  case 3:
       //código..
       break;
  default:
       //código..
       break;
}

Question: what is the default break for? Isn't it redundant? Isn't it supposed that if he went there, all the cases have already been evaluated? Why tell him to cut if there are no more cases to evaluate?

I see everywhere that they include the break in the default , and that leads me to think that I am not fully understanding this control structure

Answer:

The break statements like the default statement are optional. They are used for the purpose of separating the alternatives. In the case that you indicate if you do not put more options after the default you can leave it without the break (checking before it does not give you problems). The code would be executed in the same way, instead if you indicate for example:

switch(condicion) {
case 1:
codigo
case 2:
codigo 
break;
}

If in case the condition is 1, 2 will also be executed, you can play with that and do interesting things but what has been said, break and default are optional and if default is the last one and you see that it will not give a problem, you can not tell it you can do it without problems. If I can advise you, I would tell you to always indicate it, for security, so that it is refactorable and has consistency . We are going to say that you come back and add something else and you do not realize that the break is missing, for something so simple it can give you a hard time and it will be easier for you to debug.

I hope it helped you.

Scroll to Top