This week's book giveaways are in the Refactoring and Agile forums.
We're giving away four copies each of Re-engineering Legacy Software and Docker in Action and have the authors on-line!
See this thread and this one for details.
Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Regarding the Array Declaration

 
Sarath Koiloth Ramath
Ranch Hand
Posts: 52
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi friends,

In K&b,chapter 3 age no:196.
Array element are always given default values,regardless of where the array itself is declared or instatiated.For me this line is confusing so i wrote a program



here i am getting a compile time exception saying array is not intialised
 
B Misra
Greenhorn
Posts: 24
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
An array is first 'declared' (i.e. declaring the reference only)
then it is 'constructed' that is an array object is created in heap.
At this point The elements of the constructed array are initialized to their default values.

At next step you can intialize/ set values for each element of the array.

in you sample code if you construct the array then you'll see that the element values are initialized to default 0 (for primitive int)

public class ArrayTest {

/** Creates a new instance of ArrayTest */
public ArrayTest() {
}
public static void main(String args[]){
int arr[]= new int[5];//declared here
for(int i=0;i<5;i++)
System.out.println("Array Values --"+arr[i]);
}

}
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic