• 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

Final variables in switch

 
Ranch Hand
Posts: 32
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
 
Ranch Hand
Posts: 55
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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):
 
Greenhorn
Posts: 5
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
 
Greenhorn
Posts: 9
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
 
I can't take it! You are too smart for me! Here is the tiny ad:
a bit of art, as a gift, the permaculture playing cards
https://gardener-gift.com
reply
    Bookmark Topic Watch Topic
  • New Topic