• Post Reply Bookmark Topic Watch Topic
  • New Topic

final variable  RSS feed

 
Will Dev
Ranch Hand
Posts: 31
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello Everyone

Could someone please assist me with a better understanding of why making this variable final at line 3, allows the code to compile. Is the variable at line 13 not out off scope.?

 
Junilu Lacar
Sheriff
Posts: 11494
180
Android Debian Eclipse IDE IntelliJ IDE Java Linux Mac Spring Ubuntu
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It has to do with when the expression (percent < 10) is evaluated and whether the certainty of executing the body of the if-statement on line 8 can be determined at compile time.  When you declare the percent variable as final, that will make the conditional expression on line 8 a constant expression because all its terms are constants. Basically, the compiler can see percent is always going to be 0.0 so it can already determine that the if condition will always be true and therefore the body of the if-statement will always be executed. Try changing the value on line 3 to 20 instead of 0 and you'll get the same compile-time error as you would by not declaring percent as final. You'll also get a warning about dead code in the if-statement body.

When you don't declare percent as final, then the compiler will assume that it can be any value so since you have no other statements that would initialize those local variables, there's a possibility that you would execute line 13 with uninitialized variables.

The initializations you make to same-name variables on line 4 does not come into play in your calc method because they are not in scope. The variables that you refer to on line 13 are the local ones declared on line 7.
 
Henry Wong
author
Sheriff
Posts: 23295
125
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

As a side note to what Junilu already mentioned, making line 3 final, just to allow the code to compile is quite silly.  After all, what if you actually want to change the variable?  A better solution is to guarantee that the variables declared at line 7 are initialized -- at least with some default values (if you can't determine what those values should be at the declaration).

Henry
 
Will Dev
Ranch Hand
Posts: 31
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you for the information. It was a question on a mock exam which I wanted to make sure i understood.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!