3

is it considered bad practice to write a switch case statement with a comma such as this:

switch(name)
{
case 'a', 'A' :
break;
}

Rather than

switch(name)
{
case 'a':
case 'A':
break;
}

Just curious as my code seems to run fine either way but I want to get into the habit of using the proper/most accepted way.

AWcode
  • 45
  • 4
  • 2
    It's a "new" (proposed in 2017, released with Java 12 in 2019) feature http://openjdk.java.net/jeps/325 , so I'd imagine while team working with legacy code will frown if you include it, but for your own project and any new codebase, I don't think anyone will complaint – Martheen Dec 02 '20 at 03:47

3 Answers3

5

It's not bad practice. In fact, it's considered concise and time-efficient.

Take a look at the following code that you have

switch(name){
    case 'a', 'A' :
        break;
}

The equivalent without using commas would be:

switch(name){
    case 'a':
        break;
    case 'A':
        break;
}

And the if-else equivalent would be:

if(name=='a'){
    //Do something
}else if(name=='A'){
    //Do something
}

Of these, the first example took a mere 36 characters to type. The latter took 49, and the last one took 37 characters.

Moral? Using the comma is definitely more concise and time-efficient that using two cases with a single result. Even the if statements would be more concise.

Spectric
  • 30,714
  • 6
  • 20
  • 43
3

CheckStyle, the defacto standard for java style, has no check for this.

Do whatever is easiest to read.

I would say though use only one style or the other in any given switch statement.

Bohemian
  • 412,405
  • 93
  • 575
  • 722
-3

From JavaDocs: https://docs.oracle.com/javase/tutorial/java/nutsandbolts/switch.html

class SwitchDemo2 {
    public static void main(String[] args) {

        int month = 2;
        int year = 2000;
        int numDays = 0;

        switch (month) {
            case 1: case 3: case 5:
            case 7: case 8: case 10:
            case 12:
                numDays = 31;
                break;
            case 4: case 6:
            case 9: case 11:
                numDays = 30;
                break;
            case 2:
                if (((year % 4 == 0) && 
                     !(year % 100 == 0))
                     || (year % 400 == 0))
                    numDays = 29;
                else
                    numDays = 28;
                break;
            default:
                System.out.println("Invalid month.");
                break;
        }
        System.out.println("Number of Days = "
                           + numDays);
    }
}
Hung Vi
  • 490
  • 4
  • 16
  • 2
    Those aren't the javadoc, that's a tutorial; the comma thing is a new feature, and the tutorial simply hasn't been updated yet. – rzwitserloot Dec 02 '20 at 03:44
  • 1
    Newer tutorials already recommended them https://developer.ibm.com/languages/java/tutorials/java-theory-and-practice-6/ – Martheen Dec 02 '20 at 03:47