• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Final variables in switch

 
Seema Ahuja
Ranch Hand
Posts: 32
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 55
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 9
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic