Java Programming - Lesson 5

Java Arrays Explained: Declaration, Initialisation, Indexing, Length and Multidimensional Arrays

Introduction

One of the fundamental concepts every aspiring Java programmer must understand is the use of arrays.

Imagine developing a programme that needs to store the examination scores of 100 students. Creating 100 separate variables would be inconvenient, difficult to manage and unnecessarily complicated.

Fortunately, Java provides a more organised approach through arrays.

An array allows you to store multiple values of the same data type under a single variable name. Rather than declaring numerous individual variables, you can create one array and access its contents whenever necessary.

In this tutorial, you will learn how to declare, initialise and access arrays in Java. You will also discover how to determine their lengths, process their elements using loops, create larger arrays and work with multidimensional structures.

Let's get started!

1. What Is an Array in Java?

An array is an object that stores a fixed number of values of the same data type.

For example, an integer array can store several whole numbers, while a string array can store several text values.

Consider this example:

int[] scores = {75, 82, 90, 68, 95};


Instead of creating five separate integer variables, we have stored all five scores in one array called scores.

The array contains:

75

82

90

68

95

Each value occupies a particular position within the array.

Arrays are particularly useful when working with collections of related information, such as student scores, product prices, employee numbers, temperatures and other sets of data.

2. Declaring an Array

Before using an array, we must declare a variable that can refer to it.

The general syntax is:

dataType[] arrayName;


Here are some examples:

int[] numbers;

double[] prices;

float[] temperatures;

String[] names;

char[] letters;


The data type determines the kind of values the array can store.

For example:

int[] represents an array of integers.

double[] represents an array of double-precision decimal numbers.

float[] represents an array of floating-point numbers.

String[] represents an array of strings.

char[] represents an array of characters.

You may also encounter declarations such as:

int numbers[];


This is also valid Java syntax, although placing the square brackets beside the data type is generally clearer and commonly preferred.

3. Initialising an Array

Declaring an array variable does not automatically create an array object.

We must initialise it before using it.

One way is to use an array initialiser:

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


This creates an array containing five integers.

Another approach is to use the new keyword:

int[] numbers = new int[5];


This creates an integer array with five positions.

Because Java automatically assigns default values to array elements, the initial contents will be:

0

0

0

0

0


We can subsequently assign values to individual positions:

numbers[0] = 10;

numbers[1] = 20;

numbers[2] = 30;

numbers[3] = 40;

numbers[4] = 50;


Both approaches create arrays, but the first initialises the array with specified values immediately, while the second creates an array of a specified size that can be populated later.

4. Understanding Array Indexing

An array's index identifies the position of an individual element.

One important rule in Java is that array indexing starts at zero, not one.

Consider:

int[] values = {1, 1, 2, 3, 5, 8, 13, 21, 34};


The elements and their corresponding indexes are:

Index

Element

0

1

1

1

2

2

3

3

4

5

5

8

6

13

7

21

8

34


To access an element, we write the array name followed by its index in square brackets.

For example:

System.out.println(values[4]);


Output:

5


Although the index is 4, the element is the fifth one because counting begins at zero.

This is an important concept to remember when writing Java programmes.

5. Understanding ArrayIndexOutOfBoundsException

Java does not allow us to access an array position that does not exist.

Suppose we have:

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


This array contains five elements.

Its valid indexes are:

0, 1, 2, 3, 4


If we attempt to access:

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


Java throws an exception:

ArrayIndexOutOfBoundsException


Why?

Because index 5 is outside the valid range of the array.

This is a common programming error, particularly among beginners.

To prevent it, always ensure that the index you use is within the valid range.

6. Determining the Length of an Array

Java provides a built-in property called length that tells us the number of elements an array contains.

For example:

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


System.out.println(numbers.length);


Output:

5


Notice that length is written without parentheses.

It is a property of the array, not a method.

If an array has a length of five, its valid indexes are:

0 to 4


The general rule is:

Last valid index = Array length - 1

This relationship is extremely important when working with loops and array elements.

7. Iterating Through an Array Using a For Loop

Sometimes we need to access every element of an array rather than just one.

Java's for loop provides a convenient way to accomplish this.

Example:

public class ArrayExample {


    public static void main(String[] args) {


        int[] values = {1, 1, 2, 3, 5, 8, 13, 21, 34};


        for (int index = 0; index < values.length; index++) {


            System.out.println(

                "Value " + index + " is " + values[index]

            );


        }

    }

}


Output:

Value 0 is 1

Value 1 is 1

Value 2 is 2

Value 3 is 3

Value 4 is 5

Value 5 is 8

Value 6 is 13

Value 7 is 21

Value 8 is 34


Let's understand how the loop works.

Initialisation:

int index = 0;


The loop begins with an index of zero.

Condition:

index < values.length


The loop continues as long as the index is less than the array's length.

Increment:

index++


After each repetition, the index increases by one.

This allows the programme to visit every element, beginning with the first and ending with the last.

There is also a simplified loop known as the enhanced for loop, which is useful when you need to process every element without explicitly managing its index.

Example:

for (int value : values) {

    System.out.println(value);

}


This displays all the values in the array.

8. Why Java Arrays Have Fixed Sizes

One characteristic of Java arrays is that their size cannot be changed after creation.

For example:

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


This array has five positions.

Attempting to assign another value at index five:

values[5] = 60;


will produce an ArrayIndexOutOfBoundsException.

This is because the array's valid indexes are only zero through four.

If we need additional storage space, we must create another array.

9. Creating a Larger Array

Suppose we have an array containing five integers, but we later discover that we need space for twenty integers.

We can create a new array:

int[] moreValues = new int[20];


This creates a new integer array with twenty positions.

Its indexes range from zero to nineteen.

All twenty elements are initially set to zero.

However, creating a new array does not automatically transfer the contents of the original array.

We need to copy those values separately.

10. Copying Array Elements Using System.arraycopy()

Java provides a convenient method called System.arraycopy() for copying elements from one array to another.

Its general syntax is:

System.arraycopy(

    sourceArray,

    sourcePosition,

    destinationArray,

    destinationPosition,

    length

);


The five arguments mean:

sourceArray: The array from which elements will be copied.

sourcePosition: The starting index in the original array.

destinationArray: The array receiving the copied elements.

destinationPosition: The starting index in the destination array.

length: The number of elements to copy.

Let's examine a complete example:

public class ArrayCopyExample {


    public static void main(String[] args) {


        int[] values = {1, 1, 2, 3, 5, 8, 13, 21, 34};


        int[] moreValues = new int[20];


        System.arraycopy(

            values,

            0,

            moreValues,

            0,

            values.length

        );


        moreValues[9] = 55;


        System.out.println(moreValues[9]);

        System.out.println(moreValues[10]);


    }

}


Output:

55

0


The original nine elements are copied into the new array.

We then assign 55 to index nine.

Index ten has not been assigned another value, so it retains its default integer value of zero.

Important: System.arraycopy() requires valid source and destination ranges. The source must contain the requested number of elements, and the destination must have sufficient space.

11. Understanding Multidimensional Arrays

Sometimes, storing information in a single row of values is insufficient.

For example, imagine developing a programme that stores the examination scores of students across several subjects.

A two-dimensional arrangement may be more convenient.

Java allows us to create arrays of arrays.

A two-dimensional array is declared using two pairs of square brackets:

int[][] matrix;


This means that matrix refers to an array whose elements are themselves arrays of integers.

We can initialise it as follows:

int[][] matrix = {

    {10, 20, 30},

    {40, 50, 60},

    {70, 80, 90}

};


This arrangement resembles a table containing three rows and three columns.

We can access an individual element using two indexes:

System.out.println(matrix[0][2]);


Output:

30


The first index identifies the inner array, while the second identifies the element within that inner array.

12. Ragged or Jagged Arrays

An interesting feature of Java's arrays of arrays is that the inner arrays do not have to contain the same number of elements.

This arrangement is known as a ragged array or jagged array.

Example:

int[][] raggedMatrix = {

    {1, 2, 3},

    {4, 5},

    {6, 7, 8, 9}

};


The structure contains:

First inner array: Three elements.

Second inner array: Two elements.

Third inner array: Four elements.

Unlike a traditional rectangular table, the rows have different lengths.

We can access an element using two indexes:

System.out.println(raggedMatrix[0][2]);


Output:

3


We can also access other elements:

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


Output:

5


And:

System.out.println(raggedMatrix[2][3]);


Output:

9


This flexibility makes ragged arrays useful when different groups of data have different numbers of elements.

Remember that Java technically implements multidimensional structures as arrays of arrays. This is why individual rows can have different lengths.

13. Practical Exercise: Putting Your Knowledge to Work

Now that you understand the basic concepts, try the following exercises.

Exercise 1: Creating an Array

Create an integer array called ages containing the following values:

18, 21, 25, 30, 35


Display the contents of the array.

Exercise 2: Accessing Elements

Using your ages array, display:

The first element.

The third element.

The last element.

Exercise 3: Finding Array Length

Write a statement that displays the total number of elements in your array.

Exercise 4: Using a Loop

Write a for loop that displays every element in the array.

Exercise 5: Creating a Larger Array

Create another integer array with ten positions and copy the original five elements into it using System.arraycopy().

Exercise 6: Working with Two-Dimensional Arrays

Create a two-dimensional integer array containing three rows and three columns. Display the element in the second row and third column.

14. Key Lessons to Remember

Before moving on, make sure you understand these important points:

An array stores multiple values of the same data type.

Array indexes begin at zero.

The first element is at index zero.

The last valid index is always length - 1.

The length property tells us the number of elements in an array.

A for loop can be used to process array elements.

Java arrays have fixed sizes after creation.

A larger array can be created when additional storage is required.

System.arraycopy() can copy elements from one array to another.

Java supports arrays of arrays, including ragged arrays.

Conclusion

Arrays are among the most useful foundational structures in Java programming.

They make it easier to organise, store and process related information without declaring numerous individual variables.

From storing simple lists of numbers to organising information into rows and columns, arrays provide a foundation for more advanced programming concepts.

As you continue learning Java, you will encounter arrays in many practical applications, including data processing, mathematical

calculations, application development and software engineering.

The best way to master arrays is to practise declaring them, accessing their elements, processing them with loops and experimenting with different array structures.

Watch the accompanying video tutorial via the following link:

https://youtu.be/DzxkHg1Odek?si=H4dfephCYahgxDJEi

Keep learning, keep practising and keep building!

Creative Skills & Hobbies Hub – Where Creativity, Knowledge, and Inspiration Thrive!


Comments

Popular Posts