What are arrays in Java?

Introduction to arrays

Arrays are the most widely used data structure in the Java programming language. Arrays are used to store a group of homogeneous data elements.

By homogeneous data elements, we mean that all items must have the same datatype or they may be Object types.

The array type supports primitive or object types, and the items can be arrays or any other data structures declared by the user.

%0 node_1 1 node_2 2 node_3 3 node_1636548548630 4 node_1636548589831 5
Arrays in Java

How to define an array

Arrays are defined by using square brackets ([]) after the data type.

For example, int [] is an array of integers, where each element of the array is of data type int.

Array declaration and initialization

An array is declared by specifying the data type, name, and length. The syntax to declare an array is as follows:


<dataType>[] arrayName = new <dataType>[<length>];
Array Declaration and Initialization
1 of 5

The following code segment shows an example of an array declaration:


int [] marks = new int [4]; 

This code segment declares an array marks of length 4. The code allocates memory to hold four integers and assigns the address of the first three-element.

The array can be used as shown below:


marks [0]=10; 
marks [1]=20; 
marks [2]=30;
marks [3]=40;

The code segment above allocates memory for 4 elements and assigns values to all of them.

class HelloWorld {
public static void main( String args[] ) {
// array declaration
int [] marks = new int [4];
// array initialization
marks [0]=10;
marks [1]=20;
marks [2]=30;
marks [3]=40;
// iterating over the array
for (int i = 0; i < marks.length; i++) {
System.out.printf( "\nmarks[%d] -> %d",
i, marks[i]);
}
}
}

The code widget above demonstrates the concepts covered in this shot. Click the “Run” button to execute the code to print all the elements of the array.

Free Resources