Java Arrays
Java Arrays
Arrays are used to store multiple values in a single variable, instead of declaring
separate variables for each value.
Array is a very common type of data structure which contains all the data values of
the same data type. The data items put in the array are called elements and the first
element in the array starts with index zero.
Declaring Arrays
This declaration declares an array named num that contains 10 integers. When the
compiler encounters this declaration, it immediately sets aside enough memory to
hold all 10 elements.
A program can access each of the array elements (the individual cells) by referring
to the name of the array followed by the subscript denoting the element (cell). For
example, the third element is denoted num[2].
Example:
class Testarray{
public static void main(String args[]){
int a[]=new int[5];//declaration and instantiation
a[0]=10;//initialization
a[1]=20;
a[2]=70;
a[3]=40;
a[4]=50;
//traversing array
for(int i=0; i<a.length; i++)//length is the property of array
System.out.println(a [ i ] );
}
}
For-each Loop for Java Array
We can also print the Java array using for-each loop. The Java for-each loop prints
the array elements one by one. It holds an array element in a variable, then executes
the body of the loop.
class Testarray1{
public static void main(String args[ ] ) {
int arr[ ] = {33,3,4,5};
//printing array using for-each loop
for (int i : arr)
System.out.println( i );
}
}