Java Array is a data structure type which is used to store multiple variables of the same type. Arrays can hold Primitives as well as Object.
Note*: Array will always be an Object in Heap. No matter what it store, primitives or Object.
Array Declaration (Syntax)
Array of Primitives
//Single Dimensional Array int arr; //recommended int arr; //Multi Dimensional Array int arr; //recommended int arr; int arr;Array Of Objects
Array Of Object
//Single Dimensional Array String arr; //recommened String arr; //Multi Dimensional Array String arr; //recommened String arr; String arr;
Note: You cannot include size of array in declaration.
Declaration only doesn’t create array object in heap.
Constructing an Java Array
This is the step where array object will be created on heap. As once created size of the array can not be changed, hence size of the array needs to be provided at the time of constructing it. This size will be used by JVM while creating array object on Heap.
Note: Size of the array means how much element an array can contains.
One Dimensional Array
New keyword will be used to construct one/multi dimensional array.
int arr; //declares a new array arr = new int; One Dimensional Array
Two Dimensional Array
These are array of arrays. So a two dimensional array is array of arrays of int. So when you say, you are creating two dimensional array of Long primitive it means it will be an array containing multiple elements which in itself an array of Long.
int arr; arr = new int;
Note: Only first part(First Dimension is required) needs the size and not the all.
Once arrays created and space assigned to it next thing would be to add elements in it. Initialization of array is the place where we can do this(Adding Element in array).
Single Dimensional Array
int arr = new int; arr = 0; arr = 1; int arr = new int; // Multi Dimensional Array arr = 0; arr = 1;
Java Array Cheat-sheet
- Arrays are always created in HEAP.
- Arrays can contain both Primitives and Objects.
- Size of Array can not be included in Declaration.
- Declaration doesn’t create array object in heap.