This week's book giveaway is in the General Computing forum. We're giving away four copies of Arduino in Action and have Martin Evans, Joshua Noble, and Jordan Hochenbaum on-line! See this thread for details.
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
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
posted
0
Hi Kiran Thanks a lot for the explanation Debanjana
I agree. Here's the link: http://ej-technologies/jprofiler - if it wasn't for jprofiler, we would need to
run our stuff on 16 servers instead of 3.