Popular Searches
Popular Course Categories
Popular Courses

Introduction to Arrays in Java

Introduction to Arrays in Java

Arrays and Multidimensional Arrays

Introduction to Arrays in Java

Course: Core Java Training

Topic: Introduction to Arrays in Java

Course Link: Core Java Training Course

Demo Link: Register for a Free Course Demo

Official Website: JustAcademy


1. Introduction to Arrays in Java

An array in Java is a data structure used to store multiple values of the same data type under a single variable name. Instead of creating separate variables for every value, an array allows programmers to organize related values in a sequence and access each value using an index.

For example, if a program needs to store the marks of five students, it can use five separate variables. However, when the number of values increases, managing individual variables becomes inconvenient. An array provides a more organized solution.

Without an array:

int mark1 = 75;
int mark2 = 82;
int mark3 = 90;
int mark4 = 68;
int mark5 = 88;

Using an array:

int[] marks = {75, 82, 90, 68, 88};

Both approaches store five marks, but the array makes it easier to process all the values using loops and other programming techniques.

2. What Is an Array?

An array is an object in Java that stores a fixed number of elements of a specified type. Its size is determined when the array is created and cannot be changed afterward.

Important characteristics of Java arrays include:

  • Same element type: A primitive-type array stores values of one primitive type, such as int, double, or char. An object array stores references compatible with its declared reference type.
  • Fixed length: The number of elements is established when the array is created.
  • Zero-based indexing: The first element is at index 0.
  • Indexed access: Individual elements can be accessed or updated using their indexes.
  • Object-based structure: Arrays are objects in Java, including arrays of primitive values.
  • Default initialization: Array elements receive default values when an array is created using new.
  • Efficient access: An element can be accessed directly by its valid index.

3. Why Are Arrays Used in Java?

Arrays are useful whenever a program must store and process a collection of related values. They reduce repetitive code and work naturally with loops, calculations, searching, sorting, and data processing.

Use Case Example Purpose
Student records int[] marks Store student marks.
Product prices double[] prices Store prices of products.
Temperature readings float[] temperatures Record temperatures over time.
Character processing char[] letters Store individual characters.
Boolean values boolean[] results Store true-or-false results.
Object collections String[] names Store references to strings.

4. Types of Arrays in Java

Arrays are commonly classified according to their dimensions.

4.1 One-Dimensional Array

A one-dimensional array stores elements in a single sequence. Each element is accessed using one index.

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

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

Output:

10
30

4.2 Two-Dimensional Array

A two-dimensional array is an array whose elements are themselves arrays. It is often used to represent tables, grids, and matrices.

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

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

Output:

2
6

4.3 Multidimensional Arrays

Java supports arrays containing other arrays across multiple levels. For example, a three-dimensional array can represent grouped tables or layered data. Java multidimensional arrays are arrays of arrays, so the lengths of inner arrays can differ.

int[][][] data = new int[2][3][4];

data[0][1][2] = 100;

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

Output:

100

5. Declaring an Array in Java

Array declaration specifies the type of elements that the array will hold and declares a variable capable of referring to an array.

Syntax:

dataType[] arrayName;

Another valid declaration style is:

dataType arrayName[];

Examples:

int[] numbers;
double[] prices;
char[] letters;
boolean[] status;
String[] names;

The square brackets indicate that the variable is an array reference. The preferred convention is to place the brackets next to the data type, as in int[] numbers, because it makes the array type easier to identify.

Important: Declaring an array variable does not by itself create an array object. The variable must be assigned an existing array or a newly created array before its elements can be accessed.

6. Creating an Array Using the new Keyword

The new keyword creates an array object with a specified length. The array's elements are automatically initialized to the default value for their type.

Syntax:

dataType[] arrayName = new dataType[size];

Example:

public class ArrayCreation {
    public static void main(String[] args) {
        int[] numbers = new int[5];

        System.out.println(numbers.length);
        System.out.println(numbers[0]);
    }
}

Output:

5
0

Here, new int[5] creates an integer array containing five elements. The initial value of each element is 0, and the length is 5.

7. Initializing an Array in Java

Initialization means assigning values to the elements of an array. Java provides several ways to initialize arrays.

7.1 Initialization at Declaration

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

Java determines the length from the number of values provided. In this example, the array contains five elements.

7.2 Creating and Assigning Values Separately

int[] numbers = new int[3];

numbers[0] = 100;
numbers[1] = 200;
numbers[2] = 300;

Each value is assigned using its index. Because array indexes begin at zero, the final element of this three-element array is at index 2.

7.3 Using an Array Initializer with new

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

This form is useful when an array initializer is assigned in a context where the array type must be explicit. When the array variable is declared in the same statement, the shorter form int[] numbers = {10, 20, 30}; is also valid.

8. Understanding Array Indexes

An index is the numeric position used to access an element in an array. Java uses zero-based indexing, meaning the first element is at index 0, the second is at index 1, and so on.

Consider this array:

int[] numbers = {15, 25, 35, 45, 55};
Index Value
0 15
1 25
2 35
3 45
4 55

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

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

Output:

15
45

For a non-empty array, the last valid index is always arrayName.length - 1.

9. Accessing Array Elements

Array elements can be read individually or processed through loops. Direct access is useful when the required index is already known.

public class AccessArray {
    public static void main(String[] args) {
        String[] fruits = {"Apple", "Mango", "Orange"};

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

Output:

Apple
Mango
Orange

Accessing an element does not remove or change it. It simply reads the value stored at that position.

10. Updating Array Elements

Array elements can be changed after an array has been created. Assign a new value to a valid index to update that element.

public class UpdateArray {
    public static void main(String[] args) {
        int[] marks = {70, 80, 90};

        marks[1] = 85;

        System.out.println(marks[1]);
    }
}

Output:

85

The value at index 1 changes from 80 to 85. The array still contains three elements.

11. Finding the Length of an Array

Every Java array has a public final field named length. It returns the total number of elements the array can hold, not the number of non-default or non-null elements.

public class ArrayLength {
    public static void main(String[] args) {
        int[] numbers = {10, 20, 30, 40};

        System.out.println("Array length: " + numbers.length);
    }
}

Output:

Array length: 4

Remember: Use array.length for arrays and string.length() for strings. Arrays do not use parentheses after length.

12. Default Values in Java Arrays

When an array is created with new, Java initializes each element automatically. The default value depends on the element type.

Element Type Default Value Example
byte 0 byte[] values = new byte[3];
short 0 short[] values = new short[3];
int 0 int[] values = new int[3];
long 0L long[] values = new long[3];
float 0.0f float[] values = new float[3];
double 0.0d double[] values = new double[3];
char '\u0000' char[] values = new char[3];
boolean false boolean[] values = new boolean[3];
Reference types null String[] names = new String[3];

These default values apply to array elements created by Java. Local variables that refer to arrays must still be initialized before they can be used.

13. Traversing an Array Using a for Loop

Traversing an array means visiting its elements one by one. A traditional for loop is useful when the index is required or when processing elements in a particular order.

public class TraverseArray {
    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

The loop starts with i = 0, continues while i < numbers.length, and increments i after each iteration. This condition prevents the loop from attempting to access an invalid index.

14. Traversing an Array Using an Enhanced for Loop

The enhanced for loop, also called the for-each loop, provides a concise way to read every element when the index is not needed.

public class EnhancedForLoop {
    public static void main(String[] args) {
        String[] names = {"Amit", "Neha", "Ravi"};

        for (String name : names) {
            System.out.println(name);
        }
    }
}

Output:

Amit
Neha
Ravi

Use the enhanced for loop for straightforward element processing. Use a traditional loop when you need the index, need to update specific positions, or need to traverse in a custom order.

15. Performing Calculations on Array Elements

Arrays can be used to calculate totals, averages, minimum values, and maximum values.

15.1 Calculating the Sum

public class ArraySum {
    public static void main(String[] args) {
        int[] numbers = {10, 20, 30, 40};
        int sum = 0;

        for (int number : numbers) {
            sum += number;
        }

        System.out.println("Sum: " + sum);
    }
}

Output:

Sum: 100

15.2 Calculating the Average

public class ArrayAverage {
    public static void main(String[] args) {
        int[] marks = {70, 80, 90, 60};
        int total = 0;

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

        if (marks.length > 0) {
            double average = (double) total / marks.length;
            System.out.println("Average: " + average);
        }
    }
}

Output:

Average: 75.0

The cast (double) total ensures that division can produce a decimal result. The length check avoids division by zero when the array is empty.

16. Finding the Largest and Smallest Elements

To find the maximum or minimum, initialize a tracking variable with the first element and compare the remaining elements against it. The array must contain at least one element for this approach.

public class MinMaxArray {
    public static void main(String[] args) {
        int[] numbers = {25, 10, 45, 5, 30};

        if (numbers.length > 0) {
            int largest = numbers[0];
            int smallest = numbers[0];

            for (int number : numbers) {
                if (number > largest) {
                    largest = number;
                }

                if (number < smallest) {
                    smallest = number;
                }
            }

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

Output:

Largest: 45
Smallest: 5

17. Understanding ArrayIndexOutOfBoundsException

An ArrayIndexOutOfBoundsException occurs when code attempts to access an index that is outside the valid range of an array. For an array of length five, valid indexes are 0 through 4.

Incorrect example:

int[] numbers = {10, 20, 30};
System.out.println(numbers[3]);

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

Correct example:

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

if (numbers.length > 0) {
    System.out.println(numbers[numbers.length - 1]);
}

Output:

30

Best practices for preventing index errors:

  • Use i < array.length as the normal loop condition.
  • Remember that the first index is zero.
  • Check the array length before accessing elements when the array might be empty.
  • Do not assume that an array's final index equals its length.

18. Arrays of Strings and Other Objects

Arrays can store references to objects, including strings and custom class instances. When an object array is created using new, each reference initially contains null until an object is assigned.

public class StringArray {
    public static void main(String[] args) {
        String[] cities = new String[3];

        cities[0] = "Mumbai";
        cities[1] = "Pune";
        cities[2] = "Delhi";

        for (String city : cities) {
            System.out.println(city);
        }
    }
}

Output:

Mumbai
Pune
Delhi

A declared object array does not automatically create the individual objects. For example, creating Student[] students = new Student[3]; creates an array of three references, but each reference is initially null until a Student object is assigned.

19. Comparing Arrays with Individual Variables

Feature Individual Variables Arrays
Storage Each value has a separate variable. Related values are grouped in one array.
Access Uses individual variable names. Uses indexes.
Iteration Usually requires repetitive statements. Can be processed with loops.
Length No shared collection length. Provides the length field.
Data type Each variable has its own declared type. Elements follow the array's component type.
Size changes Not applicable as a collection. Length cannot change after creation.

20. Advantages of Arrays in Java

  • Organized storage: Related values can be grouped under one variable name.
  • Fast indexed access: Elements can be accessed directly by a valid index.
  • Easy iteration: Loops simplify processing many values.
  • Reduced repetition: Common operations can be written once and applied to every element.
  • Useful for algorithms: Arrays support searching, sorting, counting, and mathematical calculations.
  • Support for multidimensional data: Nested arrays can represent matrices and grids.

21. Limitations of Arrays in Java

  • Fixed size: An array cannot grow or shrink after creation.
  • Type restrictions: Array elements must be compatible with the declared component type.
  • Index errors: Invalid indexes can cause runtime exceptions.
  • Insertion and deletion: Inserting or removing elements within an array often requires shifting values or creating a new array.
  • Limited built-in operations: Arrays do not provide all the convenience methods available in collection classes.

When a collection needs to grow or shrink frequently, classes such as ArrayList may be more appropriate. Arrays remain useful when fixed-length storage and direct indexed access are suitable for the problem.

22. Common Mistakes When Working with Arrays

Mistake Why It Is a Problem Correct Practice
Using index 1 for the first element Java indexes start at zero. Use index 0.
Accessing index array.length This index is outside the valid range. Use array.length - 1 for the last element when non-empty.
Using i <= array.length in a loop The loop eventually accesses an invalid index. Use i < array.length.
Using an array before assigning it A local array reference may not have been initialized. Create or assign the array first.
Assuming object elements are automatically created Reference-array elements initially contain null. Create and assign objects where required.
Dividing by the array length without checking An empty array has length zero. Handle the empty-array case before calculating an average.

23. Best Practices for Using Arrays

  • Choose meaningful names, such as studentMarks, productPrices, or temperatures.
  • Use the preferred declaration format, such as int[] numbers.
  • Use array.length rather than hard-coded lengths when traversing arrays.
  • Check for empty arrays before accessing the first element or performing calculations that require at least one element.
  • Validate indexes when they come from user input or calculations.
  • Use enhanced for loops when indexes are unnecessary.
  • Use traditional for loops when indexes are required.
  • Choose an appropriate collection when the number of elements must change dynamically.
  • Use clear methods to separate tasks such as calculating totals, searching, and displaying values.

24. Practical Project: Student Marks Analyzer

Objective: Create a Java program that stores marks in an array, displays all marks, calculates the total and average, and identifies the highest and lowest marks.

Complete program:

public class StudentMarksAnalyzer {
    public static void main(String[] args) {
        int[] marks = {78, 85, 92, 67, 88};

        if (marks.length == 0) {
            System.out.println("No marks available.");
            return;
        }

        int total = 0;
        int highest = marks[0];
        int lowest = marks[0];

        System.out.println("Student Marks:");

        for (int i = 0; i < marks.length; i++) {
            System.out.println("Student " + (i + 1) + ": " + marks[i]);

            total += marks[i];

            if (marks[i] > highest) {
                highest = marks[i];
            }

            if (marks[i] < lowest) {
                lowest = marks[i];
            }
        }

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

        System.out.println("Total Marks: " + total);
        System.out.println("Average Marks: " + average);
        System.out.println("Highest Marks: " + highest);
        System.out.println("Lowest Marks: " + lowest);
    }
}

Output:

Student Marks:
Student 1: 78
Student 2: 85
Student 3: 92
Student 4: 67
Student 5: 88
Total Marks: 410
Average Marks: 82.0
Highest Marks: 92
Lowest Marks: 67

Concepts practiced:

  • Declaring and initializing an array.
  • Accessing array elements by index.
  • Traversing an array using a loop.
  • Calculating a sum and average.
  • Finding the highest and lowest values.
  • Handling the empty-array case.

25. Practice Exercises

  1. Declare an integer array containing five numbers and print every element.
  2. Create an array of ten integers and display its length.
  3. Write a program to calculate the sum of all elements in an array.
  4. Write a program to calculate the average of a set of marks.
  5. Find the largest and smallest elements in an integer array.
  6. Count how many even and odd numbers appear in an array.
  7. Search for a particular number and print its index if found.
  8. Print an array in reverse order without changing the original array.
  9. Count the occurrences of a specified value in an array.
  10. Create a two-dimensional array and display its values using nested loops.

26. Interview Questions and Answers

Q1. What is an array in Java?

An array is an object that stores a fixed number of elements of a specified component type and provides indexed access to those elements.

Q2. Why do array indexes start at zero?

Java uses zero-based indexing, so the first element is accessed with index 0. This convention is common in many programming languages and works naturally with array-offset calculations.

Q3. How do you declare an array?

An array can be declared using syntax such as int[] numbers;. This declares a variable that can refer to an integer array.

Q4. How do you create an array?

Use the new keyword with a component type and length, such as int[] numbers = new int[5];.

Q5. Can the length of an array be changed after creation?

No. An array's length is fixed after it is created. To use a different length, create another array and copy the required values if necessary.

Q6. How can you find the length of an array?

Use the array's length field, for example, numbers.length.

Q7. What is the default value of an integer array element?

An integer array created with new initializes each element to 0.

Q8. What happens if an invalid index is used?

Accessing an index outside the valid range throws an ArrayIndexOutOfBoundsException.

Q9. What is the difference between a traditional for loop and an enhanced for loop?

A traditional for loop provides direct access to the index and greater control over traversal. An enhanced for loop provides a concise way to process each element when the index is not needed.

Q10. Can an array store different data types?

A primitive array stores values of its declared primitive type. A reference array stores references compatible with its declared component type. An Object[] can hold references to different object types, but primitive values must be boxed when stored as elements.

Q11. What is the difference between array length and String length?

Arrays use the field array.length, whereas strings use the method string.length().

Q12. What is a multidimensional array?

A multidimensional array is an array whose elements are other arrays. A two-dimensional array is often used to represent rows and columns, but its inner arrays do not have to be equal in length.

27. Quick Revision Checklist

  • An array stores a fixed number of elements.
  • Array indexes begin at zero.
  • The final valid index of a non-empty array is length - 1.
  • Use dataType[] name to declare an array.
  • Use new dataType[size] to create an array with a specified length.
  • Array elements receive default values when created with new.
  • Use indexes to access and update individual elements.
  • Use array.length to determine the number of elements.
  • Use traditional or enhanced for loops to traverse an array.
  • Handle empty arrays and invalid indexes carefully.
  • Use nested arrays to represent two-dimensional or multidimensional data.
  • Consider collections such as ArrayList when a resizable structure is required.

28. Conclusion

Arrays are a fundamental part of Core Java programming. They allow related values to be stored in a structured way, accessed using indexes, and processed efficiently with loops. Understanding array declaration, creation, initialization, indexing, traversal, and common errors provides a strong foundation for learning searching, sorting, multidimensional arrays, and Java collections.

To learn more about Java programming, explore the Core Java Training Course, register for a course demo, or visit the JustAcademy website.

whatsapp