| Author |
Final variables in switch
|
Seema Ahuja
Ranch Hand
Joined: Feb 01, 2006
Posts: 32
|
|
I hv a doubt here. we all know that final variables cannot be changed. so how come the following code works? can anyone please tell me why is it letting me modify the final variable x?? Thanks
|
 |
steven gerrard
Ranch Hand
Joined: Jan 21, 2006
Posts: 55
|
|
ur not modifying the final variable since x is final x-1 is another final value of x does not change its like saying case (y=x-1):
|
 |
vignesh kaladi
Greenhorn
Joined: Feb 01, 2006
Posts: 5
|
|
hi here final valued not changed; class vignesh { public static void main(String[] args) throws Exception { final int x =2; for(int z =0;z<4;z++) { switch(x) { case x: System.out.println("One");break; case x-1: System.out.println("two");break; case x-2: System.out.println("zero"); } } } } o/p: one one one one
|
 |
Sumit Jain
Greenhorn
Joined: Jan 11, 2006
Posts: 9
|
|
Basically, key word final is acting a constant to a variable. so ,final int x =2; means x = 2 and is fixed(Const)through out the code. Now for case x: //nothing but x=2; case x-1://it will not assign the value to x but it wiil evalute as (2-1) = 1. case x-2://same as above except evalute as (2-2) = 0. So, In a nutcell you can't modify the value of x but you can use it for any mathematical expression as constant. Hope It will help. Regards, Sumit Jain
|
 |
 |
|
|
subject: Final variables in switch
|
|
|