Reputation: 71
I am a rookie in Java Programming. I am clearing all my concepts before making a step ahead. I was reading an array chapter which says the basic structure to create an array is:
Type[] var_name = new Type[limit];
I was going through some slides of opencourseware. In these slides, they inserted a class name into the type of the array. For example:
public class Baby {
Baby[] siblings;
}
Can someone explain me what is the difference between the basic array structure and the structure written inside class.
Upvotes: 3
Views: 689
Reputation: 14642
I think this may just be confusion about what constitutes a type. For the reference:
Type[] var_name = new Type[limit]
"Type" must be replaced with any primitive type (int, double, etc.) as well as any Class (Baby, in your case), such as:
String [] string_array = new String[10];
If that's not the issue you're having, the other difference between the two statements is that the first actually creates an array of size "limit" and assigns it to the variable var_name... whereas in the Baby declaration, only the member variable "siblings" in the Baby class is declared. That variable can hold a Baby array, but that array has not yet been created. In the Baby constructor, you might see something like:
Baby() {
siblings = new Baby[100];
}
This would create an array of Baby class object references of size 100, and assign it to the siblings member of the instance of Baby being created.
Upvotes: 5
Reputation: 7494
An array basically is a block of contiguous memory which can contain either primitive datatypes or objects of type that you create. Java is a statically typed language - you have to specify the type of the parameter at compile time. So you specify the type at the time you declare the array even though when you initialize it, you are only initializing a contiguous block of memory. By specifying the type, the compiler knows that this memory is to hold an object or a primitive of that 'Type'.
Type[] type = new Type[size];
the above line of code creates a block of contiguous memory of size 'size'. It holds elements of type 'Type' (in this case simply a placeholder for the type of elements you want the array to hold). Notice that you have to specify the type here.
When you have the line:
Baby[] siblings;
you are declaring the array. You still have not initialized it. Before using this, you should initialize it as:
siblings = new Baby[size];
It is only at this point that memory is allocated for this array.
Upvotes: 0
Reputation: 1110
Baby[] sibling
is just a declaration of array. It indicates compiler that Baby
contains a variable which is of type array.
The first line you mentioned is "declaring" an array as well as "initializing" it.
By initializing compiler allocates memory as per the size of array. This is when actual values can be inserted in array variable.
Upvotes: 0