Hey,
In Flow Control and Exception Handling section, in Khalid's book, I have an excercise question:
Which of these combinations of switch expression types and case label value types are legal within a switch statement?
Select ALL valid answers:
(a) switch expression of type int and case label value of type char.
(b) switch expression of type float and case label value of type int.
(c) switch expression of type byte and case label value of type float.
(d) switch expression of type char and case label value of type byte.
(e) switch expression of type boolean and case label value of type boolean.
My answer is: (a) and (d) are correct.
But, the book answers say only (a) is correct. Explaination at the back for choice (d) as incorrect is :
" The type of the case labels must be assignable to the type of the switch
expression".
To back my answer for choice (d), I have a sample code which compiles and even runs alright.
**************************
class test174
{
public static void main(
String args[])
{
char month=65;
final byte b1=65;
final byte b2=97;
switch(month)
{
case b1:
System.out.println("65");
break;
case b2:
System.out.println("97");
break;
}
}
}
****************************
Can somebody explain why I am wrong???
Also, the following line is legal:
for(int i=0, j=5, k=56;i<5; i++) // multiple declarations of int type
{
do something;
}
but, why is the line below illegal:
for(int i=0, j=5, byte k=56;i<5; i++) //multiple declarations of multiple datatypes
{
do something;
}
Can I not declare variables of more than one primitive datatypes in the initialization section of a for loop?
Thanks in advance!!
Bye,
Tualha Khan.