The Artima Developer Community
Sponsored Link

Legacy Java Answers Forum
August 2000

Advertisement

Advertisement

This page contains an archived post to the Java Answers Forum made prior to February 25, 2002. If you wish to participate in discussions, please visit the new Artima Forums.

Message:

Here it is

Posted by Kishori Sharan on August 28, 2000 at 10:09 AM

Hi
In case of switch statement the values in each case must be covered by the range of the variable type in switch. For example
switch ( cc ) {
case val1:
case val2:
case val3:
}
If cc is of type char then val1, val2 and val3 must fall in the range of char datatype. Since -1 is not a valid value for a char data type you cannot replace any case with case -1. Again, how do you store a value of -1 in char, you cannot do that. So you cannot implement a switch with char with a value of -1 in case. However, you can implement it in a limited way as follows.
When you assign a value of -1 to a char variable then you have to do a cast.
char c = -1 ; // You cannot do that
char c = ( char ) -1 ; // valid , but the actual value assigned to c is not -1 ( because char is unsigned ) rather it is 65535.
Now, if you are sure the value of your char variable in switch can never be 65535 of if it will be 65535 then you can consider it same as -1 then you can implement your switch with -1 value.
In when you write case -1 then again java compiler will object , so just do a cast . case (char ) -1: Then following program shows you how to do that.
///////////////// Test.java/////////////////
class Test {
public static void main ( String[] args ) {

char c = ( char ) -1 ; // The actual value assigned to c is 65535, not -1
//c = 65535 ; // Try this too. It will also fall in case (char) -1 : line.
switch ( c ) {
case 0:
System.out.println ( " Hello : 0 " ) ; break;
case (char) -1 :
System.out.println ( " Hello : -1 " ) ; break;
case 1 :
System.out.println ( " Hello : 1 " ) ; break;
case 2 :
System.out.println ( " Hello : 2 " ) ; break;
}

}
}

Thanx
Kishori




Replies:

Sponsored Links



Google
  Web Artima.com   
Copyright © 1996-2009 Artima, Inc. All Rights Reserved. - Privacy Policy - Terms of Use - Advertise with Us