Submitted On 16-JAN-2001
DaleKing
It is actually a little more than syntactic sugar. It can
produce more optimal code than using if's. Consider this
switch statment using ranges:
switch( c)
{
case 'a', 'e', 'i', 'o', 'u':
System.out.println( "vowel" );
break;
case 'b'..'d', 'f'..'h', 'j'..'n', 'p'..'t', 'v'..'z':
System.out.println( "consonant" );
break;
case '0'..'9':
System.out.println( "digit" );
break;
}
Consider how you would do that in a readable fashion with
if's. What is the maximum number of comparisons. A naive
reproduction of the switch could take up to 17 comparisons.
Here is a simpler version that could take up to 9:
if( c >= 'a' && c <= 'z' )
{
if( c == 'a' || c == 'e' || c == 'i' || c == 'i' || c
== 'i' )
{
System.out.println( "vowel" );
}
else
{
System.out.println( "consonant" );
}
}
else if( c >= '0' || c <= '9' )
{
System.out.println( "digit" );
}
But that is still not optimal. Here is the pseudocode for
the trivial optimization that takes 4 comparisons worst
case:
if( c >= 'i' )
if( c >= 'p' )
if( c <= 'z' )
if( c == 'o' )
goto vowel;
else
goto consonant;
else
if( c < 'j' )
goto vowel;
else
if( c == 'o' )
goto vowel;
else
goto consonant;
else
if( c < 'a' )
if( c <= '9' )
if( c >= '0' )
goto digit;
else
if( c == 'a' )
goto vowel;
else
if( c == 'e' )
goto vowel;
else
goto consonant;
Such an optimization is simple with a switch statement, but
would be very difficult with a series of if statements.
With if statements the compiler would have to guarantee
that the value does not change.
Submitted On 07-MAR-2001
lotusalife
Both ranges and comma separated lists seem quite desirable,
from the point of view of the programmer.
Submitted On 25-JUL-2001
DaleKing
In addition it would be desirable to have some cases like:
// All values less than 56 without requiring that the
// minimum be explicitly specified.
case <56:
// How about a range check using:
case <0, >=100 : // throw Exception
One could also allow floating point values for switch
statements in which case you need to specify ranges that
include or exclude the endpoint:
// The range [0,100)
case 0.0 .. <100.0 :
// The range (0,100], the <= is redundant
case >0.0 .. <=100.0 :
Or you could figure out a way to actually specify ranges
using the parenthesis and bracket notation, but that would
probably be a major tear-up to parsing.
Submitted On 16-AUG-2002
rlorenzo
Don't ignore this improvement!... I want to see this done.
Submitted On 04-FEB-2003
manihss
I fully agree that the fall through should not have been the
default behaviour. Would be nice if it was the 'opposite' and a
fall through with an explicit 'continue'..
Submitted On 26-FEB-2004
jdcjdc
haha. This shows the superiority of Pascal/Ada (which have
this feature) over languages the hack C from which Java is
partially derived.
PLEASE NOTE: JDK6 is formerly known as Project Mustang
|