Meaningless Drivel is fun!*
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 Murach's Java Servlets and JSP this week in the Servlets 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
 
 
subject: Doubt about Final variable
 
Similar Threads
initialisation and reinitialisation doubt.....
Code output -Doubt.
Doubt in InnerClass
doubt Method local inner class
Array Initialization Doubt