This week's book giveaway is in the OCAJP forum. We're giving away four copies of OCA Java SE 8 Programmer I Study Guide 1Z0-808 and have Jeanne Boyarsky & Scott Selikoff on-line! See this thread for details.
Local array is given default values but local variables are not given. just that local array are objects stored on heap and local variables on stack makes the difference some one would say. But why variables on stack are not given default values why they are not initialised. why
look at the program below for those needing more explanation to my question.
[ March 13, 2005: Message edited by: Sneha Agrawal ]
This is an arbitrary decision by the designers. Every language is different.
One rationale: Many programmers group all the declarations at the beginning of a method and use them later or not at all. Allowing local variables to go uninitialized until used saves time in frequently called methods.
When you declare a local variable like [int i], it is only a declaration, system does not allocate memory for the variable. So it is not initialized.
But for statements like "int ia = new int;", system allocate memory on the heap for the array. Since it has memory, you have to put something in it. You cannt leave the memory empty, right? So the array is initialized. [ March 13, 2005: Message edited by: Jon Lee ]
SCJP 5.0 - 98% (2007)<br />SCWCD 1.4 - 97% (2007)
Joined: Mar 13, 2004
Actually, memory is allocated on the stack for all the local variables in a method as soon as the method is entered. The method's local variables plus some save areas for returning to the calling method are allocated together as a "stack frame" when the method is called.
Java assigns default values (0 or null) to all instance variables early in the instance creation process. It was a conscious choice not to do the same thing for local variables.