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

Doubt about Final variable

 
Debanjana Dasgupta
Ranch Hand
Posts: 101
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi
I am a silent participant of javaranch.I will be appearing for SCJP2 on the 29th of this month.
I have doubt regarding final variables.
In the following code
public class X {
final int a;
X() {
a=1;
System.out.println(a);
}
X(int i) {
a=100;
System.out.println(a);
}
public static void main(String args[]) {
X x = new X();
X Yx = new X(19);
System.out.println(x.a);
System.out.println(Yx.a);
}
}
This compiles correctly printing out 1 100 1 100
But shouldnt it give an error stating that final variable cant be assigned a value?
Again if in the above code in line 2 int a is initialised, then
it gives the error that I am expecting.
But i cannot understand why there is no error when final int a is not explicitly initialised.
Looking for an answer
Thanks
Debanjana
 
Kiran Ingale
Greenhorn
Posts: 15
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Debanjana,
'final' member variables can only be initialized in constructors, if not initialized during declaration.
In your example, final variable 'a' is being initialized in both the constructors, which is correct. If you try commenting the line that assigns value to final variable 'a' you should get a compilation error.
Hope this helps.
Good luck for your exam!!
Kiran
 
Debanjana Dasgupta
Ranch Hand
Posts: 101
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Kiran
Thanks a lot for the explanation
Debanjana
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic