Fundamentals of Arrays
Learn about array features and how to manipulate them.
In Java, an array is an object. However, we also need the help of primitive data types to declare and initialize an array object.
Primitive and nonprimitive data types
Whenever we create an array object with the help of the new keyword, some memory is allocated.
We’ve added comments in the code below to highlight the relationship between the numerical index and the elements of an array.
We get the following output when we run the code above:
An example of a primitive data type : 54
The first element of my basket : 2
The second element of my basket : 3
The code example above highlights the difference between the primitive data types and arrays.
- Line 12: It showcases the
myAgevariable of theinttype, representing a single-value primitive data type. - Lines 17–19: In contrast, the
myBasketarray demonstrates the concept of arrays, capable of storing multiple values of the same data type. By comparing these, we emphasize the contrast between a single-value variable and a multivalue container.
When we declare an array in Java, we usually get help from primitive data types. This sounds logical because we need to tell the compiler what type of array we’re creating. The memory will be allocated according to our declaration. One single exception is the String nonprimitive data type. The following example will show how we can handle that.
We get the following output when we run the code above:
The name of the student who has arrived first : John
Here, we can see a slight difference in the String nonprimitive type from the normal arrays.
Note: ...