Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

What is the difference between a rule switch and a regular switch in Java?

I couldn’t find this question anywhere else so I figured I might as well ask it. Is it purely aesthetic? Is it faster in any way? What are the main differences between the two? By regular switch, I mean

switch(var){
    case 1:
        break;
}

and by rule switch, I mean

switch(var){
    case 1 -> {}
}

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

In the regular switch you can omit to break the execution at the end of a code block. This allows a fall-through, and you can handle several different cases with the same code.

switch(var) {
    case 1:
      dosomething();
      break;
    case 2:
      dosomethindelse();
            // the break was forgotten
    case 3:
    case 4: // these cases shall work on the same code
      doanotherthing();
            // but the break was forgotten
    default:
      donothing();
}

This advantage is also a disadvantage since the break can easily be forgotten and then lead to difficult to spot bugs.

Therefore the rule switch was introduced, which – by it’s different syntax does not require a break and thus prevents such situations.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading