Arrays in Java

1. Array in Java With Examples

An array is a collection of similar types of data. It is a data structure where we store similar elements. We can store only a fixed set of elements in a Java array.

Declaring an Array

To declare an array in Java, specify the type of elements it will hold, followed by square brackets:


int[] myArray;
String[] myStringArray;
    

Initializing an Array

Arrays can be initialized when they are declared or later in the code:


// Declaration and initialization
int[] myArray = {1, 2, 3, 4, 5};

// Declaration and then initialization
int[] myArray = new int[5];
myArray[0] = 1;
myArray[1] = 2;
myArray[2] = 3;
myArray[3] = 4;
myArray[4] = 5;
    

Accessing Array Elements

Array elements are accessed using their index, which starts from 0:


int[] myArray = {1, 2, 3, 4, 5};
System.out.println("First element: " + myArray[0]); // Output: 1
System.out.println("Second element: " + myArray[1]); // Output: 2
    

Array Length

You can find the length of an array using the length property:


int[] myArray = {1, 2, 3, 4, 5};
System.out.println("Array length: " + myArray.length); // Output: 5
    

Iterating Over an Array

You can use a loop to iterate over the elements of an array:


int[] myArray = {1, 2, 3, 4, 5};
for (int i = 0; i < myArray.length; i++) {
    System.out.println("Element at index " + i + ": " + myArray[i]);
}
    

Example: Sum of Array Elements

Here's an example that calculates the sum of all elements in an array:


public class ArraySum {
    public static void main(String[] args) {
        int[] numbers = {1, 2, 3, 4, 5};
        int sum = 0;

        for (int i = 0; i < numbers.length; i++) {
            sum += numbers[i];
        }

        System.out.println("Sum of array elements: " + sum); // Output: 15
    }
}
    

Example: Finding the Maximum Element

Here's an example that finds the maximum element in an array:


public class ArrayMax {
    public static void main(String[] args) {
        int[] numbers = {1, 2, 3, 4, 5};
        int max = numbers[0];

        for (int i = 1; i < numbers.length; i++) {
            if (numbers[i] > max) {
                max = numbers[i];
            }
        }

        System.out.println("Maximum element: " + max); // Output: 5
    }
}