Java Arrays

The array data structure is a collection of same type of variables. Java arrays are used to store fixed size sequential collection of same type of elements. Items in array are called elements and they can be accessed by their index. This is how to declare, initialize and access arrays in java.

//declaring array of type integer
int[] myArray;

//allocating memory
myArray= new int[10];

//assigning values
myArray[0] = 5;
myArray[1] = 10;
myArray[2] = 15;
myArray[3] = 20;
myArray[4] = 25;
myArray[5] = 30;
myArray[6] = 35;
myArray[7] = 40;
myArray[8] = 45;
myArray[9] = 50;

//retrieving values
System.out.println(“Value at index 0 = “+ myArray[0]);
System.out.println(“Value at index 5 = “+ myArray[5]);

Processing Arrays

Usually loops are used to process arrays. We can use for loop and foreach loop to process array.

Processing Array Example

public class ArrayExample {

public static void main(String[] args) {

int[] myArray= {5,10,15,20,25,30,35,40,45,50};

int total = 0;

// processing array elements

for (int i = 0; i < myArray.length; i++) {

System.out.println(“Value at index ” + i + ” is = ” + myArray[i]);

total = total + myArray[i];

}

System.out.println(“Total is = ” + total);

}

}

Output:

Value at index 0 is = 5
Value at index 1 is = 10
Value at index 2 is = 15
Value at index 3 is = 20
Value at index 4 is = 25
Value at index 5 is = 30
Value at index 6 is = 35
Value at index 7 is = 40
Value at index 8 is = 45
Value at index 9 is = 50
Total is = 275

foreach Loop

The foreach loop makes it more easy to process arrays in java. You don’t need to use the index to access array element.

foreach Example

public class ArrayExample {

public static void main(String[] args) {

int[] myArray= {5,10,15,20,25,30,35,40,45,50};

int total = 0;

// processing array elements

for (int myVal: myArray) {

System.out.println(myVal);

total = total + myVal;

}

System.out.println(“Total is = ” + total);

}

}

Output:

5
10
15
20
25
30
35
40
45
50
Total is = 275

Leave a Reply

Your email address will not be published. Required fields are marked *