Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Agile forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

a final variable declared in a while loop

 
Marlene Miller
Ranch Hand
Posts: 1392
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 1392
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 3271
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
Sarma Lolla
Ranch Hand
Posts: 203
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 3271
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 1392
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you Corey and Sarma.
Isn't the scope of a binding different from the lifetime of a binding?
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic