Lesson 28 of 50 – Java Arrays
56%

Java Arrays

An array in Java is used to store multiple values of the same data type in a single variable. Each element is accessed using an index, and array indexes start at 0.

1. What Is an Array?

Suppose you want to store five student marks. Instead of creating five separate variables, you can use an array.

int[] marks = {75, 80, 85, 90, 95};

System.out.println(marks[0]);
System.out.println(marks[1]);
System.out.println(marks[2]);

Output:

75
80
85
An array stores multiple elements of the same declared type. Use an index to access an individual element.
2. Advantages of Arrays
  • Store multiple values in one variable.
  • Access elements using indexes.
  • Process values easily using loops.
  • Reduce the need for many separate variables.
  • Useful for storing marks, prices, names, and other collections.

Without an array:

int mark1 = 75;
int mark2 = 80;
int mark3 = 85;

Using an array:

int[] marks = {75, 80, 85};

Arrays have a fixed length after creation. If you need a collection that can grow or shrink, Java also provides classes such as ArrayList.

3. Declaring an Array

You can declare an array in either of these ways:

int[] numbers;
String[] names;
double[] prices;

The declaration specifies the type of elements the array can store.

Declaration Element Type
int[] numbers; Integers
double[] prices; Decimal numbers
char[] letters; Characters
String[] names; Strings
boolean[] answers; Boolean values
4. Creating an Array with the new Keyword

You can create an array by specifying its length using the new keyword.

int[] numbers = new int[5];

This creates an integer array containing five elements. The default value of each element is 0.

System.out.println(numbers[0]);
System.out.println(numbers[1]);
System.out.println(numbers[4]);

Output:

0
0
0

Default values include 0 for integer arrays, 0.0 for floating-point arrays, false for boolean arrays, and null for reference-type arrays such as String arrays.

5. Initializing an Array

You can initialize an array with values when declaring it.

int[] numbers = {10, 20, 30, 40, 50};

String[] names = {"Amit", "Rahul", "Priya"};

double[] prices = {99.50, 150.75, 250.00};

Example:

String[] names = {"Amit", "Rahul", "Priya"};

System.out.println(names[0]);
System.out.println(names[1]);
System.out.println(names[2]);

Output:

Amit
Rahul
Priya
6. Accessing Array Elements

Each array element has an index. The first index is 0, the second is 1, and so on.

int[] numbers = {10, 20, 30, 40, 50};

System.out.println(numbers[0]);
System.out.println(numbers[2]);
System.out.println(numbers[4]);

Output:

10
30
50
Index Value
010
120
230
340
450
7. Changing Array Elements

You can change an array element by assigning a new value to its index.

int[] numbers = {10, 20, 30, 40};

numbers[1] = 100;

System.out.println(numbers[1]);

Output:

100

The original value 20 at index 1 is replaced with 100.

Complete example:

int[] marks = {60, 70, 80};

marks[0] = 95;
marks[2] = 90;

for (int i = 0; i < marks.length; i++) {
    System.out.println(marks[i]);
}

Output:

95
70
90
8. Array Length Property

The length property returns the number of elements in an array.

int[] numbers = {10, 20, 30, 40, 50};

System.out.println(numbers.length);

Output:

5

Use the length property to loop through every element.

int[] numbers = {10, 20, 30, 40, 50};

for (int i = 0; i < numbers.length; i++) {
    System.out.println(numbers[i]);
}
For arrays, use array.length, not array.length().
9. Loop Through an Array

A for loop is commonly used to access every array element.

public class Main {
    public static void main(String[] args) {

        int[] numbers = {10, 20, 30, 40, 50};

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

Output:

10
20
30
40
50

You can also use an enhanced for loop:

int[] numbers = {10, 20, 30, 40, 50};

for (int number : numbers) {
    System.out.println(number);
}

The enhanced for loop is useful when you want to read each element without managing an index.

10. Calculate the Sum and Average of Array Elements

Calculate the sum and average of five marks.

public class Main {
    public static void main(String[] args) {

        int[] marks = {70, 80, 90, 60, 100};
        int sum = 0;

        for (int mark : marks) {
            sum += mark;
        }

        double average = (double) sum / marks.length;

        System.out.println("Total = " + sum);
        System.out.println("Average = " + average);
    }
}

Output:

Total = 400
Average = 80.0

Casting the sum to double ensures the average can include a decimal part when necessary.

11. Find the Largest and Smallest Elements

Find the largest and smallest values in an integer array.

public class Main {
    public static void main(String[] args) {

        int[] numbers = {25, 10, 85, 40, 5};

        int largest = numbers[0];
        int smallest = numbers[0];

        for (int i = 1; i < numbers.length; i++) {

            if (numbers[i] > largest) {
                largest = numbers[i];
            }

            if (numbers[i] < smallest) {
                smallest = numbers[i];
            }
        }

        System.out.println("Largest = " + largest);
        System.out.println("Smallest = " + smallest);
    }
}

Output:

Largest = 85
Smallest = 5

This example assumes the array contains at least one element. An empty array must be handled separately before accessing index 0.

12. Common Array Errors
Error Explanation or Correction
Accessing index 5 in a five-element array Valid indexes are 0 through 4.
Using different element types in a primitive int array Store values compatible with the declared type.
Using numbers.length() Use numbers.length for an array.
Using i <= numbers.length Use i < numbers.length.
Accessing an array before initializing its reference Initialize the array before using it.

Incorrect example:

int[] numbers = {10, 20, 30};

System.out.println(numbers[3]);

This throws an ArrayIndexOutOfBoundsException because the valid indexes are 0, 1, and 2.

Correct example:

System.out.println(numbers[2]);

Output: 30

13. Practice Assignments

Write Java programs to complete these assignments.

  1. Create an integer array containing five numbers and print them.
  2. Create a String array containing five student names.
  3. Print all elements using a for loop.
  4. Print all elements using an enhanced for loop.
  5. Calculate the sum of all array elements.
  6. Calculate the average of five student marks.
  7. Find the largest number in an array.
  8. Find the smallest number in an array.
  9. Count how many even numbers are in an array.
  10. Search for a particular number in an array.
Tip: Practice array indexes and the length property before moving to multidimensional arrays.

🧠 Quick Quiz

1. What is the index of the first element in a Java array?




2. Which property returns the number of elements in an array?




3. What happens when you access an invalid array index?