wood burning stoves*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Doubt about Final variable Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of The Java EE 7 Tutorial Volume 1 or Volume 2 this week in the Java EE forum
or jQuery UI in Action in the JavaScript forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Doubt about Final variable" Watch "Doubt about Final variable" New topic
Author

Doubt about Final variable

Debanjana Dasgupta
Ranch Hand

Joined: Aug 11, 2000
Posts: 101
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

Thanks<br /> <br />Debanjana<br /> <br />SCJP2<br />SCEA
Kiran Ingale
Greenhorn

Joined: Sep 11, 2000
Posts: 15
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

*****************************************<BR>I listen to Hindi songs at <A HREF="http://www.hindigeet.com" TARGET=_blank rel="nofollow">http://www.hindigeet.com</A>
Debanjana Dasgupta
Ranch Hand

Joined: Aug 11, 2000
Posts: 101
Hi Kiran
Thanks a lot for the explanation
Debanjana
 
Consider Paul's rocket mass heater.
 
subject: Doubt about Final variable