File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Final variables in switch Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Make it so: Java DB Connections & Transactions this week in the JDBC forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Final variables in switch" Watch "Final variables in switch" New topic

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??

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

Joined: Feb 01, 2006
Posts: 5
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++)
case x: System.out.println("One");break;
case x-1: System.out.println("two");break;
case x-2: System.out.println("zero");

Sumit Jain

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.
Sumit Jain
I agree. Here's the link:
subject: Final variables in switch
It's not a secret anymore!