This week's book giveaway is in the Kotlin forum.
We're giving away four copies of Kotlin in Action and have Dmitry Jemerov & Svetlana Isakova on-line!
See this thread for details.
Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

why local variable need to be initialized?  RSS feed

 
bhuvi mdu
Greenhorn
Posts: 17
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

Can anyone say why local variable need to be initialized? I knew that if it is not initialized it will throw compile time error but i wanna know the reason why it shud be initialized?


bhuvi
 
Timmy Marks
Ranch Hand
Posts: 226
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
When you allocate resources for a local variable, Java doesn't write a value into the memory. The reason you get an error is because Java makes sure you give it a value before you use it. Sun realized that this can be a difficult problem to diagnose in C code, because you don't get help from the compiler, so they decided to check it at compile time.
 
bhuvi mdu
Greenhorn
Posts: 17
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
thanx for ur answer Timmy Marks



bhuvi
 
Layne Lund
Ranch Hand
Posts: 3061
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
From my point of view, the reason is because that's the way the creators of Java said we have to do it. It's very likely that their reasons for this decision are along the lines of what Timmy said above.

Layne
 
David Harkness
Ranch Hand
Posts: 1646
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Note that every variable must be initialized before it is used. It's easy to miss this because the JVM initializes all instance and static members whether you want it to or not.

I suspect the reason for the difference in behavior involved many late nights of frenetic nerf gun battles in the Sun hallways.

James: Auto-initializing variables is ugly and wasteful! The compiler run your code through a proof engine to ensure every constructor call results in exactly one initialization per variable.

Patrick: Do you realize how hard that would be? *ducks* Besides, 83.2% of all class members are initialized to the same defaults, so we save the developers keystrokes!

James: Hey! I got you, cheater! You're out.

Patrick: No way man -- prove it!

Yes, I think that's exactly how it went down. Such reverent times they were. . .
 
Consider Paul's rocket mass heater.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!