GeeCON Prague 2014*
The moose likes Java in General and the fly likes Final variable return zero before initialize Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


JavaRanch » Java Forums » Java » Java in General
Bookmark "Final variable return zero before initialize" Watch "Final variable return zero before initialize" New topic
Author

Final variable return zero before initialize

Siva Masilamani
Ranch Hand

Joined: Sep 19, 2008
Posts: 385
Hi

I have doubt about the following program



I know java does not initialize the final variable instead it expect us to provide the value.

But in the above case why it is returning j value as zero.

How come in line 2 j value becomes zero?


SCJP 6,SCWCD 5,SCBCD 5

Failure is not an option.
John de Michele
Rancher

Joined: Mar 09, 2009
Posts: 600
Siva:

Actually, all member variables are defaulted to null for references, false for booleans, and 0 for other primitives, regardless of being final. Since your method doesn't actually change the value of j (it just assigns the value of itself to itself), your answer is 0.

John.
Seetharaman Venkatasamy
Ranch Hand

Joined: Jan 28, 2008
Posts: 5575

final variable gets the value before the constructor finish the execution .so you assign the method inside the constructor

final int j;


Hope this helps
Siva Masilamani
Ranch Hand

Joined: Sep 19, 2008
Posts: 385
John de Michele wrote:Siva:

Actually, all member variables are defaulted to null for references, false for booleans, and 0 for other primitives, regardless of being final. Since your method doesn't actually change the value of j (it just assigns the value of itself to itself), your answer is 0.

John.


But i have read somewhere that java does not assign default value to final variable because if it assigs default value then it can not be changed,so it expect us to provide the value.

Could you please explain this?
John de Michele
Rancher

Joined: Mar 09, 2009
Posts: 600
Siva:

Well, your program ran, so whoever wrote that was incorrect. If Java didn't assign a default, you'd probably get a random number. I did a test to check all three cases:

I consistently get this result:

So clearly, final variables get assigned defaults.

John.
Siva Masilamani
Ranch Hand

Joined: Sep 19, 2008
Posts: 385
Thanks John for your valuable information.

I appreciate it.
John de Michele
Rancher

Joined: Mar 09, 2009
Posts: 600
Siva:

Glad I could help.

John.
 
Don't get me started about those stupid light bulbs.
 
subject: Final variable return zero before initialize