Java Arrays


Arrays in Java are used to store multiple values of the same type in a single variable, instead of declaring separate variables for each value. They are one of the most common data structures in programming and make it easier to manage large collections of data efficiently.

What Is an Array in Java?

An array is a group of elements of the same data type, stored in a continuous block of memory. Each element in an array can be accessed using its index number, where the first element starts from index 0. For example, an integer array can hold several integer values such as marks of students, scores, or even numbers in a series.

Example:

int[] marks = {85, 90, 78, 92, 88};

Here, marks is an array of integers that stores five values. The index of these values will be 0, 1, 2, 3, and 4 respectively.

Declaring and Initializing Arrays

There are two main ways to create arrays in Java — by declaration followed by initialization, or by direct initialization.

Declaration and Initialization in Separate Steps

int[] numbers = new int[5];
numbers[0] = 10;
numbers[1] = 20;
numbers[2] = 30;
numbers[3] = 40;
numbers[4] = 50;

Here, an integer array of size 5 is declared. Each element is then assigned a value individually.

Direct Initialization

You can also declare and initialize an array in a single line like this:

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

This method is more concise and commonly used when you already know the values to store.

Accessing Array Elements

Each element in an array can be accessed using its index. The index always starts at 0, so to access the first element, you use index 0.

Example:

System.out.println(numbers[0]); // prints 10
System.out.println(numbers[4]); // prints 50

If you try to access an index that does not exist, such as numbers[5], it will result in an ArrayIndexOutOfBoundsException.

Modifying Array Elements

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

numbers[2] = 99;
System.out.println(numbers[2]); // prints 99

Arrays in Java are mutable, which means their elements can be modified, but the array size cannot change once it’s created.

Array Length Property

Every array has a built-in property called length, which returns the total number of elements in the array.

System.out.println(numbers.length); // prints 5

You can use this property to loop through the entire array without manually counting the elements.

Looping Through Arrays

Arrays are often used with loops to perform operations on each element. You can use either a for loop or an enhanced for-each loop.

Using a for Loop

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

Using a for-each Loop

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

The enhanced for loop is simpler and more readable, especially when you only need to read array elements.

Types of Arrays

Java supports both single-dimensional and multi-dimensional arrays.

Single-Dimensional Array

This is the most common type, where elements are stored in a single row.

String[] fruits = {"Apple", "Banana", "Cherry"};

Multi-Dimensional Array

You can also create arrays that contain other arrays, such as a 2D array (matrix).

int[][] matrix = {
    {1, 2, 3},
    {4, 5, 6},
    {7, 8, 9}
};

To access an element in a 2D array, you need two indexes — one for the row and one for the column.

System.out.println(matrix[1][2]); // prints 6

Iterating Through a 2D Array

You can use nested loops to access all elements in a two-dimensional array.

for (int i = 0; i < matrix.length; i++) {
    for (int j = 0; j < matrix[i].length; j++) {
        System.out.print(matrix[i][j] + " ");
    }
    System.out.println();
}

This will print the elements of the matrix in a row-column format.

Advantages of Arrays

  • Arrays make it easy to manage multiple related data items.

  • They allow fast access to elements using indexes.

  • Arrays are more memory-efficient than declaring many separate variables.

Limitations of Arrays

  • The size of an array is fixed once created; you cannot add or remove elements dynamically.

  • All elements must be of the same data type.

  • Adding or deleting elements requires creating a new array.

In cases where you need a flexible collection, Java provides alternatives like ArrayList in the java.util package.

Summary of the Tutorial

Arrays are one of the most essential data structures in Java. They let you store multiple values of the same data type in a single variable, making data handling more organized and efficient. You can access, modify, and loop through elements easily, whether in single or multi-dimensional forms. However, arrays have a fixed size, so for dynamic data storage, you may use collections like ArrayList.


Practice Questions

  1. Write a Java program to create an array of five integers and print all elements using a for loop.

  2. Create a program that calculates the sum of all elements in an integer array using a for-each loop.

  3. Write a Java program that finds the largest and smallest numbers in an array of integers entered by the user.

  4. Develop a program that takes an array of integers and prints all even numbers from it using a loop.

  5. Write a Java program to reverse the elements of an array and print the reversed array.

  6. Create a Java program that copies all elements from one array into another using a loop.

  7. Write a program to count how many times a specific number appears in an array.

  8. Develop a program that takes an array of strings and prints the length of each string.

  9. Write a Java program that sorts an integer array in ascending order without using built-in methods.

  10. Create a program that takes two arrays of equal length and prints their element-wise sum into a third array.


Try a Short Quiz.

coding learning websites codepractice

No quizzes available.

Go Back Top