This week's giveaway is in the Android forum.
We're giving away four copies of Android Security Essentials Live Lessons and have Godfrey Nolan on-line!
See this thread for details.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Why local variables does not get initialized? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Android Security Essentials Live Lessons this week in the Android forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Why local variables does not get initialized?" Watch "Why local variables does not get initialized?" New topic
Author

Why local variables does not get initialized?

sarah mrinmoyee
Greenhorn

Joined: Jul 12, 2012
Posts: 8
void method(){
int i ; // not get initialized.
}


anyone??
assumption: For saving memory??

Keep rocking!
Greg Charles
Sheriff

Joined: Oct 01, 2001
Posts: 2840
    
  11

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

Joined: Jul 09, 2001
Posts: 1167
A good discussion about it at Why compiler does not provides default values to local variables?

Regards,
Dan


William Butler Yeats: All life is a preparation for something that probably will never happen. Unless you make it happen.
sarah mrinmoyee
Greenhorn

Joined: Jul 12, 2012
Posts: 8
-Thank you, Dan for the reference.

-sarah

 
wood burning stoves
 
subject: Why local variables does not get initialized?
 
Similar Threads
Memory allcocation at time of loading class..
Final instance variables
instance initializers
Array 's == Ques
loading the class and initialization of class