aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes a final variable declared in a while loop Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Spring in Action this week in the Spring forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "a final variable declared in a while loop" Watch "a final variable declared in a while loop" New topic
Author

a final variable declared in a while loop

Marlene Miller
Ranch Hand

Joined: Mar 05, 2003
Posts: 1391
It looks like j is being assigned to three times. But j is final. How do you explain this?

[ March 11, 2003: Message edited by: Marlene Miller ]
Marlene Miller
Ranch Hand

Joined: Mar 05, 2003
Posts: 1391
I suppose this is part of the reason...
JLS 14.4.4 Execution of Local Variable Declarations
A local variable declaration statement is an executable statement. Every time it is executed, the declarators are processed in order from left to right. If a declarator has an initialization expression, the expression is evaluated and its value is assigned to the variable.

[ March 11, 2003: Message edited by: Marlene Miller ]
Corey McGlone
Ranch Hand

Joined: Dec 20, 2001
Posts: 3271
Marlene,
I believe this is really a scope issue. The final variable is local to the loop block. Therefore, when the loop goes back to the evaluation statement to determine if it should execute again, the final variable has gone out of scope. Therefore, the next time you would iterate through the loop, you'd be creating a brand new final variable and assigning to it just once.
I hope that helps,
Corey


SCJP Tipline, etc.
Sarma Lolla
Ranch Hand

Joined: Oct 21, 2002
Posts: 203
This is a very good question.
By looking at the final reserved word you get the impression that this is a compile time error as the final variable is getting assigned again and again. But as others mentioned already the variable gets created every time and thus compiler has no problem with this code.
People hang around here to see these type of simple yet misleading questions.
Thanks for letting us know about these traps...
Corey McGlone
Ranch Hand

Joined: Dec 20, 2001
Posts: 3271
You can be sure that the compiler is smart enough to catch when a final variable might be assigned more than once. Try compiling this and see what you get:
Marlene Miller
Ranch Hand

Joined: Mar 05, 2003
Posts: 1391
Thank you Corey and Sarma.
Isn't the scope of a binding different from the lifetime of a binding?
 
Don't get me started about those stupid light bulbs.
 
subject: a final variable declared in a while loop