What is Java Array?
An array is a group of elements of similar data type.
Array elements can be either primitives(such as int, float, double) or objects(such as String, Person, Dog etc.).
Array itself is an object irrespective of its element types and is stored on the heap.

If an array contains primitive elements, it should be called an array of primitives but it is incorrect to say primitive array as there is no such thing as primitive array.

Array declaration
An array in java can hold elements of only one type. Thus, it is declared by stating the type of elements that it will contain.
Type should be followed by square brackets and a user defined name of the variable that will represent the array.
Following examples declare an array of int, double, string, char, objects etc.

//array of int
int[] integers;
// array of double
double [] numbers;     //recommended
double numbers[];      // allowed but not recommended
// array of objects
Dog[] dogs;

It is not permitted to provide the size of array at the time of declaration and will raise a compiler error.
This is because memory is not allocated for the array till it is created.
Initialize array
Till now we only declared the array which tells JVM about the type of elements the array will contain.
Defining or initializing an array means actually constructing the array where we specify the size of the array(number of elements in the array) so that JVM can allocate memory for it.

An array can be created in two ways:
1. Using new array
Create array just like an object is created using new operator. Example,

// create array of five integers
int[] numbers = new int[5];
// create array of five dog objects   
Dog[] dogs = new Dog[5];
It is not possible to change the size of array after it is created. You can not increase or decrease the number of elements that an array can hold after it is created.

2. Direct initialization
Provide elements right at the time of declaration. You do not need to provide the size when using this method since it is calculated by the number of elements given while initialization.
Also, elements of the array are provided within curly braces.
Example,

// create an array of 6 elements
int[] numbers = {2, 3, 45, 6, 7, 8};   
// create array of 2 dog objects
Dog[] dogs = {new Dog("a"), new Dog("b")};

It is also possible to split array declaration and initialization in two different statements as shown below.

int[] numbers;    // declare int array
numbers = new int[5];   // create an array of 5 elements

This is usually done when the size of the array at the time of declaration is not known.
But you can not do this when directly initializing array elements.
That is, following will invite a compiler error.

int[] numbers;    // declare array
numbers = {2, 3, 45, 6, 7, 8};  // NOT allowed
Array memory representation
An array is an object and objects in java are stored on heap memory.
Thus, an array of primitive elements(such as integer) will be stored as shown below.
representation of array of primitive elementsAn array whose elements are themselves objects is represented as below.

representation of array of objects

Default values of elements of an integer array is 0 while all elements of an object array will be initialized to null after the array is created but no elements are assigned to it.

Accessing Array elements
Array elements are index based with index starting from 0 to length of array – 1.
That is, for an array of five elements, its index will range from 0 to 4 with index of first element being 0, second element 1 and last element 3.
For accessing an array element, its index is used. Syntax to access an individual array element is by using the name of array reference variable followed by its index in square brackets.
Thus, for an array of 5 elements,

numbers[1]  will return the second array element
numbers[0] will return the first array element
numbers[4] will return the last array element

If you try to access array index which is outside the length of array, then a java.lang.ArrayIndexOutOfBoundsException is raised.
Example, for an array of length 5, accessing indexes above 4 and below 0 will raise this exception.

Array length
Length or size of array is the total number of elements in the array and can be found using its length property.
Remember the index of array elements will be from 0 to length – 1. Example,

// initialize array of strings
String[] colors = {"Violet", "Blue", "White", "Black"};
System.out.println(colors.length);   // will print 4

Loop over array
Since an array is a collection of elements, it can be iterated over by a loop.
This loop can be a normal loop which uses index based iteration such as for or while loop or enhanced for loop(also referred as for-each loop).
Index based looping
This approach initializes a for loop from 0 till length of array – 1. In every iteration, you can access the current array element using its index. Example,

int[] numbers = {23, 45, 62, 1};  // length is 4
// loop from 0 till 3
for(int index = 0; index < numbers.length - 1; index++) {
   System.out.println("Element at position " + index + " is " + numbers[index]);
}

which prints

Element at position 0 is 23
Element at position 1 is 45
Element at position 2 is 62
Element at position 3 is 1

Array foreach
This approach does not use indexing. Instead, it uses a variable which is of the same type as the array.
In every iteration, this variable contains the current array element.
This is called for-each loop or enhanced for loop in java.
Example,

// initialize array of strings
String[] languages = {"java", "python", "C#"};
System.out.println("Languages are: ");
// loop with foreach
for(String lang: languages) {
   System.out.println(lang);
}

Notice the use of colon(:) after variable name. Above code outputs

Languages are:
java
python
C#

Modifying Array elements
Elements of an array can be modified after its creation using assignment operator(=) and the element index.
Assign a new value to the element which needs to be modified using its index as shown below.

String[] fruits = {"Apple", "Banana", "Orange", "Grapes"};
fruits[1] = "Papaya";   // replace Banana with Papaya

Assigning elements to array using a loop
It is also possible to initialize array elements after its creation using a loop and assignment operator. This can only be done using index based loop and not using enhanced for loop. Example,

// create an array of 4 elements
int[] numbers = new int[4];  
// loop from 0 till 3
for(int index = 0; index < numbers.length - 1; index++) {
   // assign element to current position
   numbers[index] = index * 10;   
}
Multidimensional arrays
All the arrays demonstrated till now are one dimensional arrays. A one dimensional array contains a single element at each array location.
Type of this element is the same as that of the array.
If an array element is another array, then such array is called a multidimensional array in java.
A multidimensional array is represented as below.
Two dimensional array example
Above is an example of a two dimensional int array where element at every array index is another int array.
Note that if a the main array index does not point to another array, then it is initialized as null.
Initializing multidimensional arrays
A multidimensional array is created using multiple square brackets, one for each dimension. Example,

// create a two dimensional array
int[][] numbers = new int[4][4];
// create a one dimensional array
int[] arrayOne = new int[4];
// create another one dimensional array
int[] arrayTwo = new int[4];
// assign elements of two dimensional array
numbers[0] = arrayOne;
numbers[1] = arrayTwo;

Above example creates initializes a two dimensional or double dimensional int array. Each element of this array is another array.
Note that it is created using double square brackets.
First bracket indicates the number of elements in the main array and second bracket indicates the number of elements in element array .
Default array values
After the array is declared and initialized but its elements are not given any values, they have a default value. The default value depends on the type of array.
Below table summarizes the default values of array elements.

Array Type>Default Element Value
int0
float0.0
double0.0
booleanfalse
objectnull

Print array
An array is an object in java. If you directly print an array using System.out.print, then it will not print its element.
In order to print an array to show meaningful information, you need to take some special measures.
Refer this article to learn how to print a java array in the required format.

Click the clap if the article was useful for you.

1

Share your thoughts !!

Close Menu

Never Miss an article !

Get the new post delivered straight into your inbox, enter your email and hit the button

You have successfully subscribed to the newsletter

There was an error while trying to send your request. Please try again.

codippa will use the information you provide on this form to be in touch with you and to provide updates and marketing.