Java Lesson 15 – Arrays | Dataplexa

Arrays in Java

In real-world programs, we rarely work with just one value. Most applications deal with collections of data — such as marks of students, prices of products, or scores of players.

Java provides arrays to store multiple values of the same type under a single variable name.


Why Arrays Are Needed

Imagine storing the marks of 50 students. Without arrays, you would need 50 separate variables.

Arrays solve this problem by grouping related values together, making programs cleaner, faster, and easier to manage.


What Is an Array?

An array is a fixed-size data structure that stores multiple values of the same data type.

Each value in an array is stored at a specific position, called an index. Array indexes always start from 0.


Declaring and Initializing Arrays

There are multiple ways to create arrays in Java. Let’s start with the most common approach.

public class ArrayExample {

    public static void main(String[] args) {

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

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

Here, the array stores five integer values. Each value is accessed using its index.


Creating Arrays with Size

Sometimes, you may know the size of the array but not the values in advance.

In such cases, Java allows you to define the size first and assign values later.

public class ArraySizeExample {

    public static void main(String[] args) {

        int[] numbers = new int[4];

        numbers[0] = 10;
        numbers[1] = 20;
        numbers[2] = 30;
        numbers[3] = 40;

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

This approach is useful when values are provided dynamically.


Looping Through Arrays

Arrays become powerful when combined with loops. Loops allow Java to process all elements efficiently.

The for loop is commonly used with arrays.

public class ArrayLoopExample {

    public static void main(String[] args) {

        int[] scores = {70, 75, 80, 85};

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

The length property tells Java how many elements are in the array.


Real-World Use of Arrays

Arrays are widely used in real applications:

  • Storing exam scores or grades
  • Processing product prices
  • Managing sensor readings
  • Handling fixed-size datasets

They form the foundation for advanced data structures such as lists and collections.


Limitations of Arrays

Arrays have a fixed size. Once created, their size cannot be changed.

This limitation led to the creation of Java Collections, which you will learn about in later lessons.


What You Learned in This Lesson

  • Why arrays are needed
  • How to create and access arrays
  • How to loop through array elements
  • Where arrays are used in real programs

In the next lesson, you will begin exploring object-oriented programming concepts, which form the core of Java.