Your Page Title
🔍

    Java Arrays: An Overview

    Java provides a powerful feature that allows users to design a set of similar data types called arrays. This chapter will explain how arrays can be created and manipulated in Java, and will also discuss their implementation as objects.


    What are Arrays?

    In programming, an array is a collection of elements, all of the same type, stored at contiguous memory locations. Arrays are useful for organizing data so that related values can be easily accessed and manipulated. For example, if you have the scores of 50 students, instead of creating 50 individual variables to hold each score, you can store all scores in a single array.

    Characteristics of Arrays

    1. Fixed Size: Once declared, the size of an array cannot be changed.
    2. Same Data Type: All elements in an array must be of the same data type.
    3. Zero-Based Indexing: Array indexing starts from 0, so the first element is accessed with index 0, the second with index 1, and so on.

    Declaring and Initializing Arrays

    Declaration

    To declare an array in Java, you specify the type of elements it will hold followed by square brackets. For example:

    int[] marks;  // Declaration of an integer array

    Allocation

    After declaring an array, you need to allocate memory for it:

    marks = new int[30]; // Allocates memory for 30 integers

    Initialization

    You can also initialize an array at the time of declaration:

    int[] ages = {32, 24, 31, 25, 26}; // Declaration and initialization

    Accessing Array Elements

    You can access individual elements of an array using their index:

    int firstMark = marks[0]; // Accessing the first element

    Example Program: Average Marks Calculation

    Here’s a complete example that demonstrates how to create an array to store student marks and calculate their average:

    import java.util.Scanner;

    public class AverageMarks {
    public static void main(String[] args) {
    int i, sum = 0, avg;
    int[] marks = new int[30]; // Declaring and initializing the array
    Scanner scanner = new Scanner(System.in);

    // Input: Store data in the array
    for (i = 0; i < 30; i++) {
    System.out.print("Enter marks for student " + (i + 1) + ": ");
    marks[i] = scanner.nextInt();
    }

    // Processing: Calculate the sum of marks
    for (i = 0; i < 30; i++) {
    sum += marks[i];
    }

    // Output: Calculate and display the average
    avg = sum / 30;
    System.out.println("Average marks = " + avg);
    }
    }

    Explanation of the Program

    1. Array Declaration: The line int[] marks = new int[30]; creates an array named marks that can hold 30 integer values.
    2. Input Loop: The first for loop prompts the user to enter marks for each student, which are stored in the array.
    3. Sum Calculation: The second loop iterates through the array, summing all the marks.
    4. Average Calculation: Finally, the average is calculated and displayed.

    Array Initialization Methods

    Arrays can be initialized in different ways:

    Static Initialization:

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

    Dynamic Initialization:

    int[] numbers = new int[5]; // Creates an array with 5 elements, all initialized to 0

    Mixed Initialization:

    String[] names = new String[3];
     names[0] = "Alice"; names[1] = "Bob"; names[2] = "Charlie";

    Iterating Over Arrays

    Standard For Loop

    You can use a standard for loop to iterate through an array:

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

    Enhanced For Loop (For-Each Loop)

    The enhanced for loop simplifies iteration:

    for (int mark : marks) {
    System.out.print(mark + " ");
    }

    Using the length Property

    You can access the length of an array using the length property:

    int size = marks.length; // Gets the number of elements in the array

    Array Indexing and Bounds Checking

    Java enforces strict bounds checking. If you try to access an index that is outside the bounds of the array, an ArrayIndexOutOfBoundsException is thrown:

    int[] numbers = {1, 2, 3};
    System.out.println(numbers[3]); // This will throw an exception

    Passing Arrays to Functions

    Arrays can be passed to functions. When an array is passed to a method, a reference to the array is passed, allowing the method to modify the original array.

    Example: Passing an Array

    public class PassArrayExample {
    public static void main(String[] args) {
    int[] marks = {55, 65, 75, 85};
    modifyArray(marks); // Passes the array reference

    // Display the modified array
    for (int mark : marks) {
    System.out.print(mark + " ");
    }
    }

    static void modifyArray(int[] array) {
    for (int i = 0; i < array.length; i++) {
    array[i] *= 2; // Modifies the original array elements
    }
    }
    }

    Explanation

    1. The modifyArray method receives the reference to the marks array.
    2. Inside the method, the elements of the array are doubled.

    Returning Arrays from Functions

    You can return an entire array from a function:

    public class ReturnArrayExample {
    public static void main(String[] args) {
    int[] resultArray = createArray(); // Receives the returned array
    for (int number : resultArray) {
    System.out.print(number + " ");
    }
    }

    static int[] createArray() {
    return new int[]{10, 20, 30, 40, 50}; // Returns a new array
    }
    }

    Common Array Operations

    Java provides the Arrays class in the java.util package to perform common array operations such as sorting, searching, and filling.

    Example: Using the Arrays Class

    import java.util.Arrays;

    public class ArrayOperations {
    public static void main(String[] args) {
    int[] arr = {3, 1, 4, 1, 5, 9};

    // Sorting the array
    Arrays.sort(arr);
    System.out.println("Sorted array: " + Arrays.toString(arr));

    // Searching for an element
    int index = Arrays.binarySearch(arr, 4);
    System.out.println("Element 4 found at index: " + index);

    // Filling an array
    Arrays.fill(arr, 0); // Sets all elements to 0
    System.out.println("Array after fill: " + Arrays.toString(arr));
    }
    }

    Explanation

    • Sorting: The Arrays.sort(arr); method sorts the array in ascending order.
    • Searching: The Arrays.binarySearch(arr, 4); method searches for the element 4 and returns its index.
    • Filling: The Arrays.fill(arr, 0); method sets all elements of the array to 0.

    Arrays of Objects

    You can create arrays of objects in Java. Here’s how you can define and use an array of a custom object:

    Example: Array of Objects

    class Student {
    private String name;
    private int age;

    public Student(String name, int age) {
    this.name = name;
    this.age = age;
    }

    public void display() {
    System.out.println("Name: " + name + ", Age: " + age);
    }
    }

    public class ObjectArrayExample {
    public static void main(String[] args) {
    Student[] students = new Student[3];
    students[0] = new Student("Alice", 20);
    students[1] = new Student("Bob", 22);
    students[2] = new Student("Charlie", 21);

    for (Student student : students) {
    student.display();
    }
    }
    }

    Explanation

    • The Student class has a constructor and a method to display student details.
    • An array of Student objects is created, and individual objects are initialized and displayed.

    Multi-Dimensional Arrays in Java

    Multi-dimensional arrays are arrays of arrays. The most common type is the two-dimensional array, which can be visualized as a matrix or a table with rows and columns. Java also supports arrays with more than two dimensions, but we’ll primarily focus on two-dimensional arrays for simplicity.

    Declaring and Initializing Multi-Dimensional Arrays

    Declaration

    To declare a multi-dimensional array, you specify the type followed by multiple sets of square brackets. For example, to declare a two-dimensional array of integers:

    int[][] matrix; // Declaration of a 2D array

    Allocation

    After declaring the array, you can allocate memory for it. You can specify the number of rows and columns during allocation:

    matrix = new int[3][4]; // Creates a 2D array with 3 rows and 4 columns

    Initialization

    You can also initialize a multi-dimensional array at the time of declaration:

    int[][] matrix = {
    {1, 2, 3, 4},
    {5, 6, 7, 8},
    {9, 10, 11, 12}
    }; // A 2D array initialized with values

    Accessing Elements in Multi-Dimensional Arrays

    You can access elements in a multi-dimensional array using row and column indices. The first index specifies the row, and the second specifies the column.

    int value = matrix[1][2]; // Accesses the element in the 2nd row, 3rd column (value: 7)

    Example: Basic Operations on a Two-Dimensional Array

    Here’s a complete example that demonstrates declaring, initializing, accessing, and printing a two-dimensional array:

    public class TwoDimensionalArrayExample {
    public static void main(String[] args) {
    // Declaration and Initialization
    int[][] matrix = {
    {1, 2, 3},
    {4, 5, 6},
    {7, 8, 9}
    };

    // Accessing Elements
    int row = 1;
    int col = 2;
    System.out.println("Element at row " + row + ", column " + col + ": " + matrix[row][col]); // Outputs 6

    // Printing the Entire Array
    System.out.println("Matrix:");
    for (int i = 0; i < matrix.length; i++) { // Iterate through rows
    for (int j = 0; j < matrix[i].length; j++) { // Iterate through columns
    System.out.print(matrix[i][j] + " "); // Print each element
    }
    System.out.println(); // Move to the next line after each row
    }
    }
    }

    Explanation of the Example

    1. Matrix Declaration and Initialization: The matrix is declared and initialized with values in a single step.
    2. Accessing an Element: The program retrieves and prints the element at row 1, column 2.
    3. Nested Loops for Printing: Two nested loops are used to iterate through each element in the matrix and print it in a grid format.

    Array Length in Multi-Dimensional Arrays

    You can use the length property to determine the size of the array:

    • matrix.length gives the number of rows.
    • matrix[i].length gives the number of columns in row i.

    Example: Dynamic Initialization

    You can also create a multi-dimensional array and initialize it dynamically:

    public class DynamicTwoDimensionalArray {
    public static void main(String[] args) {
    int rows = 3;
    int cols = 4;
    int[][] matrix = new int[rows][cols]; // Dynamic allocation

    // Fill the array with values
    int value = 1;
    for (int i = 0; i < rows; i++) {
    for (int j = 0; j < cols; j++) {
    matrix[i][j] = value++;
    }
    }

    // Print the matrix
    System.out.println("Dynamic Matrix:");
    for (int[] row : matrix) {
    for (int element : row) {
    System.out.print(element + " ");
    }
    System.out.println();
    }
    }
    }

    Explanation

    1. Dynamic Allocation: The program allocates memory for a 3×4 matrix.
    2. Filling the Array: A nested loop is used to populate the array with sequential values.
    3. Printing the Matrix: The enhanced for loop prints the matrix.

    Multi-Dimensional Arrays with Different Row Sizes

    In Java, multi-dimensional arrays can have different sizes for each row, creating what is known as a “jagged array.” Here’s how to declare and initialize a jagged array:

    public class JaggedArrayExample {
    public static void main(String[] args) {
    // Jagged array declaration
    int[][] jaggedArray = new int[3][]; // 3 rows, but columns will be defined later

    // Initializing each row with different sizes
    jaggedArray[0] = new int[2]; // 2 columns
    jaggedArray[1] = new int[3]; // 3 columns
    jaggedArray[2] = new int[1]; // 1 column

    // Filling the jagged array
    int value = 1;
    for (int i = 0; i < jaggedArray.length; i++) {
    for (int j = 0; j < jaggedArray[i].length; j++) {
    jaggedArray[i][j] = value++;
    }
    }

    // Printing the jagged array
    System.out.println("Jagged Array:");
    for (int i = 0; i < jaggedArray.length; i++) {
    for (int j = 0; j < jaggedArray[i].length; j++) {
    System.out.print(jaggedArray[i][j] + " ");
    }
    System.out.println();
    }
    }
    }

    Explanation

    1. Jagged Array Declaration: The jagged array is declared with a fixed number of rows, but no fixed number of columns initially.
    2. Row Initialization: Each row is initialized with a different number of columns.
    3. Filling and Printing: A nested loop is used to fill and print the jagged array.