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.
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
.
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>];
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 declarationint [] marks = new int [4];// array initializationmarks [0]=10;marks [1]=20;marks [2]=30;marks [3]=40;// iterating over the arrayfor (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.