Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

about final variable

 
wei liu
Ranch Hand
Posts: 56
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Can the final variable be initialized in the constructor???
 
Jim Hall
Ranch Hand
Posts: 162
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yes.
A final variable can be initialized when it is declared, in an initializer block, or in a constructor.
 
Arathi Rajashekar
Ranch Hand
Posts: 112
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Final Variables:-
There are 2 types of final variables.
1) instance final vars.
2) class level (static) final vars.
According to JLS:-Instance Final Variable
"The final var has to have an explicit value by the programmer, but it can be given either in the declaration statement itself like " final int j=20;" OR in one of the FOLLOWING instance floating block (also called as instance initializers) OR in ALL CONSTRUCTORS of the given class".
In Second Case: Static final Variable
Static final vars also HAVE TO HAVE a value explicitly assigned by the programmer and this init has to happen either in the declaration statement itself like 'static final int var1=100;' OR in one of FOLLOWING static floating blocks (also called as static initializers). Also note that in both cases instance final var and static final vars, once we assigned a value means we CAN'T CHANGE them again.
Note we can't initialize static final variable in constructor

[This message has been edited by Arathi Rajashekar (edited December 21, 2001).]
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic