File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
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
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Doubt about Final variable" Watch "Doubt about Final variable" New topic

Doubt about Final variable

Debanjana Dasgupta
Ranch Hand

Joined: Aug 11, 2000
Posts: 101
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() {
X(int i) {
public static void main(String args[]) {
X x = new X();
X Yx = new X(19);
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<br /> <br />Debanjana<br /> <br />SCJP2<br />SCEA
Kiran Ingale

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!!

*****************************************<BR>I listen to Hindi songs at <A HREF="" TARGET=_blank rel="nofollow"></A>
Debanjana Dasgupta
Ranch Hand

Joined: Aug 11, 2000
Posts: 101
Hi Kiran
Thanks a lot for the explanation
I agree. Here's the link:
subject: Doubt about Final variable
It's not a secret anymore!