• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Can a final variable be changed at runtime

 
kaffo lekan
Ranch Hand
Posts: 42
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello
i need to know if a final variable can be changed at runtime.
Yes/No , please explain more.
 
Eric Edwards
Ranch Hand
Posts: 60
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by kaffo lekan:
Hello
i need to know if a final variable can be changed at runtime.
Yes/No , please explain more.

Declaring a variable as final forbids modification of the variable at runtime. Any attempt to modify the value of a final instance variable after it is initialized is a syntax error.
Hope this helps.
 
Nathan Pruett
Bartender
Posts: 4121
IntelliJ IDE Java Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
This is great! Double posts in the forum on a yes/no question and it gets a yes in one and a no in the other!
Unfortunately, this is the wrong answer... the answer in your other post ( http://www.javaranch.com/ubb/Forum33/HTML/001682.html ) is correct...
-Nate
 
Cindy Glass
"The Hood"
Sheriff
Posts: 8521
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The fact that a final variable can be initialized within it's constructor gives you the possibility of taking in a parameter at the command line and using that to set the final variable.
Be aware though that if you defer initializing a final variable, then it has to be initialized in EVERY ONE of the classes constructors, and some classes have many overloaded constructors.
In addition if you have a static final variable, it can be set in a static initializer block.
Lastly, if you have a local final variable (like inside a method) it can defer it's initializaion, allowing the value to be passed to the method at runtime.
But aside from these "construction" exceptions, Eric is correct, once initialized it can never be modified.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic