• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

switch statement

 
Ranch Hand
Posts: 151
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
hi all,
i am unable to understand how the following code is legal?
byte b = 10;
switch(b)
{
case 'a' :
break;
}
whereas
char ch='a';
byte b=ch; //Explicit cast needed to convert char to byte.
or
byte b=97;
char ch=b; //Explicit cast needed to convert byte to char.
According to Mughal book,"The case label values must be assignable to the type of integral expression used in switch statement."
could anyone explain why char the above switch statement would compile without error where as the next 2 assignment statements will give compile time errors?
thanx in advance.
rajashree.
 
Ranch Hand
Posts: 267
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
char ch='a';
byte b=ch;
here is the casting tree.
byte->short or char->int ->long & so on...
To down cast char to byte you will need an explicit cast. Rememeber that byte,short & char are imlicitly cast to int during any operation therefore this
byte b = 10;
switch(b) is legal.
Any body correct me if I am wrong..

Roopa.


Originally posted by rajashree ghatak:
hi all,
i am unable to understand how the following code is legal?
byte b = 10;
switch(b)
{
case 'a' :
break;
}
whereas
char ch='a';
byte b=ch; //Explicit cast needed to convert char to byte.
[b]or

byte b=97;
char ch=b; //Explicit cast needed to convert byte to char.
According to Mughal book,"The case label values must be assignable to the type of integral expression used in switch statement."
could anyone explain why char the above switch statement would compile without error where as the next 2 assignment statements will give compile time errors?
thanx in advance.
rajashree.[/B]


 
Ranch Hand
Posts: 464
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Rajashree...
Here is how i see it
Case 1:
From JLS:
The switch statement transfers control to one of several statements depending on the value of an expression.
SwitchStatement:
switch ( Expression ) SwitchBlock
The type of the Expression must be char, byte, short, or int, or a compile-time error occurs.
From JLS:
Every case constant expression associated with a switch statement must be assignable (�5.2) to the type of the switch Expression.
To my understanding the Case labels, have to be a type that's integer compatible (byte, short, char and int).
Wheather the case may be getting evalutated , but it compiles becoz the switch (Expression) and the Case Label, does not violate integer compatible data types

Case 2:
Implicit conversion issues MUST involve INTEGER data-type
byte b = 97; //This works fine (integer to byte)
byte b = (byte) 500; //Outa range so casting required
char ch = b; //NOPE no integer involved (byte to char) implicit //illegal (Casting required)
Hope I helped you
Please correct me if i am wrong
Ragu
 
Greenhorn
Posts: 17
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Does this mean that the expression, regardless of what is passed to it, is converted to an int.
AND
The label it is compared to is also converted to an int.
And what we end up with is an:
if(int expression == int label)
[This message has been edited by Dominic Mack (edited October 08, 2001).]
[This message has been edited by Thomas Paul (edited October 09, 2001).]
 
rajashree ghatak
Ranch Hand
Posts: 151
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
hi all,
i too have the same query as Dominic.
Conversion between char,byte and short requires explicit casting.Then how can 'a',a char value be assigned to b, a byte variable without a explicit cast in switch statement?
can anyone kindly explain?
rajashree.
 
Ragu Sivaraman
Ranch Hand
Posts: 464
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Let me tell you what i understood
I dont think they get converted to integer as a common data type
to compare between switch expression and case label constant expression
Let me give you an example
public static void main(String args[]){
System.out.println(Character.getNumericValue('a'));
char ch;

switch(ch = 'a') {
case 10:
System.out.println("This is unicode numeric value");
case 'a' :
System.out.println("This is character");
}
}
Well if there is an integer comparsion then the case 10 must have been executed rite? becoz 'a' unicode value is 10
But when you run it its actually case 'a'.
So the switch/case is evaluated based on the data-type of switch expression which have to be BSC or I
Please correct me if i am wrong
thankx
Ragu
 
Ranch Hand
Posts: 2120
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi all
Convertions between char and short/byte are regarded as narrowing and thus they will require a cast to compile. But the section 5.2 in the JLS explains that the asigment conversion allows a certain type of primitive narrowing convertion if the following is true:
" * The expression is a constant expression of type byte, short, char or int.
* The type of the variable is byte, short, or char.
* The value of the expression (which is known at compile time, because it is a constant expression) is representable in the type of the variable.
"
So if b is byte and s is short these lines compiles:
b='a';
s='a';
because 97 is value representable both in byte and short.
But these ones require a cast:
b=(byte)'\u0080';
s=(short)'\u8000';
 
Ranch Hand
Posts: 139
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
As Jose mentioned earlier,
the assignments you have question on are
not assigning compile-time constants to
variables, even though they seem to have
values within the range of the target
variables.
Therefore, if your code is changed as
follows, you won't need cast:

Hope this help.

[This message has been edited by Nain Hwu (edited October 08, 2001).]
 
Ranch Hand
Posts: 73
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
It's strange while the previous piece of code works, this one doesn't:
final byte b;
{
b=97;
char ch = b;
}
Any ideas regarding the cause? Please excuse for the "off-topic" message.
 
Ragu Sivaraman
Ranch Hand
Posts: 464
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Originally posted by Adrian Muscalu:
It's strange while the previous piece of code works, this one doesn't:
final byte b;
{
b=97;
char ch = b;
}
Any ideas regarding the cause? Please excuse for the "off-topic" message.


Implicit conversion will work under the following conditions
1. Initilization and declaration occurs in a single line of code
2. +=
3. use of final modifier to make it as a constant expression
In the above code, I believe
b= 97 is not considered as a constant expression, even though
this feature of initializing final in a constructor/instance block came in jdk version 1.2 or 1.3 (not sure)

correct me if i am wrong

 
Nain Hwu
Ranch Hand
Posts: 139
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator


t's strange while the previous piece of code works, this one doesn't:
final byte b;
{
b=97;
char ch = b;
}


Compile-time constants are defined in JLS 15.28.
In particular, see this regarding final variable:


Simple names that refer to final variables whose initializers are constant expressions


So, in order to make a final variable
as compile-time constant, it must have
a initializer when it is defined.
In other words, it can not be a blank
final, which is assigned with a value,
as you have tried.
[This message has been edited by Nain Hwu (edited October 09, 2001).]
 
rajashree ghatak
Ranch Hand
Posts: 151
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
hi all,
i just tried out foll code which give compile error asking for explicit cast
final char ch='c';
byte b='a'; //1
short s='b'; //2
byte b1=ch; //3
all the above 3 assignments require explicit cast.
why is it so when according to JLS:
Convertions between char and short/byte are regarded as narrowing and thus they will require a cast to compile. But the section 5.2 in the JLS explains that the asigment conversion allows a certain type of primitive narrowing convertion if the following is true:
" * The expression is a constant expression of type byte, short, char or int.
* The type of the variable is byte, short, or char.
* The value of the expression (which is known at compile time, because it is a constant expression) is representable in the type of the variable.
"
kindly explain.
rajashree.
 
Nain Hwu
Ranch Hand
Posts: 139
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
rajashree,
It should compile fine. Will you please show us your code?
 
Jose Botella
Ranch Hand
Posts: 2120
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
This question is very interesting:

I think the explanation can't be :


Simple names that refer to final variables whose initializers are constant expressions


because the initializer of b is 97 which is a constant expresion.
I think the compiler doesn't regard blank finals as contant expresions because they could be initialized with a different value in each constructor. Given that the aim of constants expresions is inlining of its values the compiler could not subtitute each appearance of the field by its value if there are more than one.
 
Nain Hwu
Ranch Hand
Posts: 139
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Jose,
Thanks for correction.
 
Ranch Hand
Posts: 18944
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
<pre>
class haa{
public static void main(String[] args){
final char ch='c';
byte b='a'; //1
short s='b'; //2
byte b1=ch; //3
}
}
</pre>
This code compiles just fine. Rajshree, have you figured out why it failed to compile on your machine?
Shyam
[This message has been edited by Shyamsundar Gururaj (edited October 09, 2001).]
 
Greenhorn
Posts: 16
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi! rajashree
From all the disscussion above I think there is a need to clear some concepts.
1. 'a' is not equal to a
2. 'a' is not equal to 10 . It is equal to 97
3. So far you don't mention type, compiler take 'a' as 97 or as 'a' according to where it is used. To prove my point take a look at the following code. When it is compiled it gives error ( duplicate case label ).

And this is the reason why it does not give error in your code. It take 'a' as 97, which is within the byte limit 127
One more thing byte b is not converted into int as someone mentioned in the above discussion. To prove it change 97 in the above code with 128. It will give error that found int required byte.
Avais
 
rajashree ghatak
Ranch Hand
Posts: 151
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
hi all,
thanx all for ur responses.
i just now tried once again the below code on my machine (using Windows 98 and jdk1.2.1) and again got compile error asking for explicit cast in all 3 assignments.
public static void main(String[] args)
{
final char ch='c';
byte b='a'; //1
short s='b'; //2
byte b1=ch; //3
}
in khalid book(page 48)it is given:
short val=(short)'a'; //Explicit cast needed .
also mentioned in the book(Pg.48):
Narrowing conversion between char and byte or short values on assignment always requires an explicit cast.

pls tell me why i am not able to compile it whereas others are able to?
rajashree.
 
Nain Hwu
Ranch Hand
Posts: 139
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
It compiles fine in JDK1.3.1.
It is consistent with JLS �5.2 as being mentioned in earlier
post.
As for Khalid's code in p.48, I tried without casting and got this
result, which I think is consistent with JLS.

Line "char d = b" needs a cast is expected, since the right
hand side expression is not a compile-time constant expression.
Even though it has value within the range, compiler can't assume
that.
Looks like it is a bug in Khalid's book and JDK1.2.1??

[This message has been edited by Nain Hwu (edited October 10, 2001).]
 
Greenhorn
Posts: 13
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Hi,
As Ako Ufodike wrote in his previous posting
The hirarchy follows as below(this hirarchy does not require casting):

byte->short->int->long->float->double
or
char->short->int->long->float->double.

However, the reverse of the above will always require casting.
for example
1) double d = 2.0;
float f =(float)d;

Also,
2) byte b = 7;
char c = (char)b;

3) char c= 'a';
byte b =(byte)a;
 
Nain Hwu
Ranch Hand
Posts: 139
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Ruby,


However, the reverse of the above will always require casting.


Not if the right side is an int constant which is within the range of the left side of the assignment. This is the only case
where narrowing assignment does not need an explict cast and
has roused a this interesting discussion.
In fact, your code confirmed this point:


 
rajashree ghatak
Ranch Hand
Posts: 151
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
hi all,
can anyone tell what should be the answer of the piece of code mentioned in previous post if such a Ques is asked in Certification?
should we say it compiles fine or should the answer be compile time error,needing explicit cast.
According to Nain Hwu, it compiles fine on jdk 1.3.1 but what about in jdk 1.2.1/1.2.2 ?
also is there a bug in khalid's book on pg.48 where explicit cast is needed always in narrowing conversion between char and byte or short datatypes?pls confirm.
also, will the below code compile fine which on jdk1.2.1 give compile error asking for explicit cast though it is according to
JLS �5.2 section
public static void main(String r[])
{
final byte bb = 32;
char c = bb;
}
rajashree.
 
Ranch Hand
Posts: 87
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
As far as I know neither byte nor short can be assigned to a char without casting.
Similarly, a char cannot be assigned to either byte or short without casting.
Please correct me if I am wrong.
 
Ranch Hand
Posts: 3141
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Ruby V,
Please read the JavaRanch Name Policy and re-register using a name that complies with the rules.
Thanks for your cooperation.
------------------
Jane Griscti
Sun Certified Programmer for the Java� 2 Platform
 
rajashree ghatak
Ranch Hand
Posts: 151
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
hi everyOne,
kindly look at my previous post and give ur comments.i am getting very confused since some says the code compiles fine whereas in jdk1.2.1 on my machine i am getting compile error needing explicit cast.
pls confirm.
rajashree.
 
Jose Botella
Ranch Hand
Posts: 2120
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi Rajshree
I don't know why it needs an explicit cast in jdk 2.2 but I would trust the JLS and update to 1.3
Have you tired the errata for the book?
 
Consider Paul's rocket mass heater.
reply
    Bookmark Topic Watch Topic
  • New Topic