• Post Reply Bookmark Topic Watch Topic
  • New Topic

final variables being reassigned  RSS feed

 
blossom belle
Ranch Hand
Posts: 145
1
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
why is line  A being allowed ?



OUTPUT :
0.0
30.0
60.0
90.0
120.0
150.0
180.0
210.0
240.0
270.0

percent is a final variable but it is re assigned within the loop . doesn't this violate the final rule ?
 
Andrew Nessin
Greenhorn
Posts: 3
1
  • Likes 4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
That's because the final keyword prohibits a final variable from being reassigned, but in the above loop, you're both declaring and assigning the final variable. So on each iteration of the loop, the percent variable loses its scope when the iteration ends, and on the next iteration, it's like you're declaring a brand new variable in a new scope, and its being assigned as soon as it is declared. This happens on every iteration. So it's legal.

If you happen to change your code to this:





Then you can see the compiler error that final variable can't be reassigned. Now the scope of the percent variable is same throughout the all the iterations, and you can't reassign in the same scope. Hope you got the difference.
 
blossom belle
Ranch Hand
Posts: 145
1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
thanks !
 
Don't get me started about those stupid light bulbs.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!