This week's book giveaways are in the Scala and Android forums.
We're giving away four copies each of Machine Learning Systems: Designs that scale and Xamarin in Action: Creating native cross-platform mobile apps and have the authors on-line!
See this thread and this one for details.
Win a copy of Machine Learning Systems: Designs that scale this week in the Scala forum
or Xamarin in Action: Creating native cross-platform mobile apps in the Android forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

final variables being reassigned  RSS feed

 
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 ?
 
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 !
 
I didn't do it. You can't prove it. Nobody saw me. The sheep are lying! This tiny ad is my witness!
free 1 hour java lesson
https://coderanch.com/t/695988/free-hour-java-lesson
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!