JDK-8061403 : Allow multiple constants and ranges in case labels
  • Type: Enhancement
  • Component: specification
  • Sub-Component: language
  • Priority: P4
  • Status: Closed
  • Resolution: Other
  • Submitted: 1999-09-08
  • Updated: 2014-10-17
  • Resolved: 2014-10-17
Related Reports
Duplicate :  
Relates :  
Relates :  
Description
Name: wl91122			Date: 09/08/99


It would be nice if case labels allowed several comma separated values.

switch( i )
{
   case 1,3,5,7: foo();
}

would be equivalent to the less readable version

switch( i )
{
   case 1:
   case 3:
   case 5:
   case 7: foo();
}

In addition why not allow ranges as well? The two together allow you to 
efficiently code things like:

switch( c )
{
    case 'A'-'Z','a'-'z':
        System.out.println( "letter" ); break;
    case '0'-'9':
        System.out.println( "number" ); break;
    default:
        System.out.println( "other" ); break;
}

As it stands now the only way to code this is using if statements but they 
aren't as readable as this switch statement. You can tell at a glance what 
this switch statement does. Compare that with:

if( c >= 'A' && c <='Z' || c >= 'a' && c <='z' )
    System.out.println( "letter" ); break;
else if( c >= '0' && c <= '9' )
    System.out.println( "number" ); break;
else
    System.out.println( "other" ); break;

I don't see any real problem with adding it to the language. Source code 
that uses this construct would not be backwards compatible, but neither is 
any code that uses a new API. The generated bytecode would still be 
backwards compatible.

I really wish you could get rid of the fall-through behavior for switch statements, 
but I understand that it's too late now and it must be kept that way for backwards 
compatibility.
(Review ID: 95013) 
======================================================================

Comments
The 'specification' component of the Java Bug System is for reporting technical errors and ambiguities in the text of The Java Language Specification and The JVM Specification. It is not the venue to propose new features in the Java language or JVM. Ongoing feature development is carried out in OpenJDK (http://openjdk.java.net/jeps/); corresponding enhancements to The Java Language Specification and The JVM Specification are managed through the Java Community Process (http://jcp.org/).
17-10-2014

WORK AROUND Name: wl91122 Date: 09/08/99 Use separate case labels for each case, which is less readable. Use if statements for ranges. Again, less readable. ======================================================================
13-07-2004

EVALUATION Relatively harmless syntactic sugar. gilad.bracha@eng 1999-09-08
08-09-1999