• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Final variable return zero before initialize

 
Siva Masilamani
Ranch Hand
Posts: 385
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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?

 
John de Michele
Rancher
Posts: 600
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 5575
Eclipse IDE Java Windows XP
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 385
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 600
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 385
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks John for your valuable information.

I appreciate it.
 
John de Michele
Rancher
Posts: 600
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Siva:

Glad I could help.

John.
 
I agree. Here's the link: http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic