Java array structure

I am new to Java programming. I clear all my concepts before I step forward. I read the array section that says the basic structure for creating an array is:

Type[] var_name = new Type[limit];

      

I went through a few slides of opencourseware. In these slides, they pasted the class name into the array type. For example:

public class Baby {
   Baby[] siblings;
}

      

Can someone explain to me what is the difference between the basic array structure and the structure written inside the class.

+3


source to share


3 answers


I think it might just be a confusion about what the type is. For reference:

Type[] var_name = new Type[limit]

      

"Type" should be replaced by any primitive type (int, double, etc.) as well as any class (Baby, in your case), for example:

String [] string_array = new String[10];

      



If this is not the problem you are having, the other difference between the two is that the former actually creates an array of size "limit" and assigns it to var_name ... whereas the Baby declaration only declares the member variable "brothers and sisters "in the" child "class. This variable may contain the Baby array, but this array has not been created yet. In Baby's constructor, you can see something like:

Baby() {
     siblings = new Baby[100];
}

      

This will create an array of 100 Baby references and assign it to the sibling member of the created Baby instance.

+5


source


Baby[] sibling

is just an array declaration. It tells the compiler that it Baby

contains a variable that has an array of types.
The first line you mentioned is the "declaration" of the array as well as the "initialization". At initialization, the compiler allocates memory according to the size of the array. This is when actual values ​​can be inserted into an array variable.



0


source


An array is basically a block of contiguous memory that can contain either primitive data types or objects of the type you create. Java is a statically typed language - you need to specify the type of the parameter at compile time. This way, you specify the type when you declare the array, even though when you initialize it, you only initialize a contiguous block of memory. By specifying a type, the compiler knows that this memory is intended to hold an object or primitive of that type.

Type[] type = new Type[size];

      

the above line of code creates a block of contiguous memory of size "size". It contains elements of type "Type" (in this case, just a placeholder for the type of elements you want to store in the array). Note that you must specify the type here.

When you have a line:

Baby[] siblings;

      

you are declaring an array. You still haven't initialized it. Before using this, you must initialize it like:

siblings = new Baby[size];

      

Only at this moment is memory allocated for this array.

0


source







All Articles