Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Why local variables does not get initialized?

 
sarah mrinmoyee
Greenhorn
Posts: 8
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
void method(){
int i ; // not get initialized.
}


anyone??
assumption: For saving memory??

Keep rocking!
 
Greg Charles
Sheriff
Posts: 2985
12
Firefox Browser IntelliJ IDE Java Mac Ruby
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Well, not that. Local variables are stored on the stack, and they take the same amount of space whether or not they are initialized. That isn't to say that instantiating objects doesn't take memory space, but those are stored in heap memory, and the local variables just reference them. What happens in other languages, like C++, is that uninitialized variables just hold whatever random data was at the memory location they are using, and so errors can be very hard to catch. Something might work fine, and then you recompile and it breaks.

Java decided that fields would be implicitly initialized to 0, false, null, etc., based on type, and that local variables would have to be initialized before being used, otherwise the compiler would complain. Why the difference between fields and local variables? I can't actually remember. I've been doing it so long, it just seems natural to me.
 
Dan Drillich
Ranch Hand
Posts: 1183
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
A good discussion about it at Why compiler does not provides default values to local variables?

Regards,
Dan
 
sarah mrinmoyee
Greenhorn
Posts: 8
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
-Thank you, Dan for the reference.

-sarah

 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic