| Author |
switch construct
|
Amit Kumar Ch
Greenhorn
Joined: Jul 19, 2005
Posts: 15
|
|
Hi, The following peice of code is from the K & B book. 1 final int a=1; 2 final int b; 3 b=2; 4 int x=0; 5 switch(x) 6 { 7 case a: //This line compiles fine. 8 case b: // This line gives a compiler error. can anyone please tell me why line 8 gives an error?
|
 |
Nilesh Raje
Ranch Hand
Joined: Aug 02, 2005
Posts: 153
|
|
Hello Amit, What I think in this case is you need to intialize the final variable b in the declaration line itself. You need to intialize the final variable where you have declared it. 1 final int a=1; 2 final int b; 3 b=2; 4 int x=0; 5 switch(x) 6 { 7 case a: //This line compiles fine. 8 case b: // This line gives a compiler error.
|
Thanks and Regards,<br />Nilesh<br />SCJP 1.4, SCWCD 1.4
|
 |
swanand paranjape
Greenhorn
Joined: Aug 24, 2005
Posts: 4
|
|
case expressions must be constant expressions , and in given code b is blank final variable , sa at compile time compiler checks the constant expression for case statement, and b get value 2 at run time please correct if any thing is wrong swanand
|
 |
Georgy Bolyuba
Ranch Hand
Joined: Feb 18, 2005
Posts: 162
|
|
Originally posted by Amit Kumar Ch: 1 final int a=1; 2 final int b; 3 b=2;
There is a difference between 'a' and 'b'. 'a' is initialized with a compile-time constant expression and is final. So we call it 'a constant variable'. 'b' is final but it is blank final variable. A blank final is a final variable whose declaration lacks an initializer. That's why you cannot use 'b' in the way you are trying to use it.
|
SCJP 1.4 (100%) Done.<br />SCJD (URLyBird 1.2.3 Started)
|
 |
A Kumar
Ranch Hand
Joined: Jul 04, 2004
Posts: 973
|
|
Hi, We are assigning value to b...and final means once u assign a value ...we cannot change it... So b does have a value...if a is initiliased with a value so does b holds a value..but after a step later... Also suppose we pass a value to a function whose parameter is final ..then how does ..the function doesnt give any compiler error? Tx
|
 |
 |
|
|
subject: switch construct
|
|
|