Skip to main content

Command Palette

Search for a command to run...

Arrays in Java

Published
5 min read
Arrays in Java

On Day 4, the focus is on arrays in Java, one of the most important data structures that allow storing multiple elements of the same type in a single variable.


1. Introduction to Arrays

  • An array in Java is a collection of elements, all of the same type, stored in a contiguous block of memory.

  • Arrays provide a way to group multiple values under a single variable name and access them by an index.

Key Characteristics:

  • Arrays are of fixed size. Once initialized, the size cannot be changed.

  • Elements in an array are indexed starting from 0.

  • All elements of an array must be of the same data type (e.g., int[], String[], double[]).


2. Declaring and Initializing Arrays

Declaration: To declare an array, specify the data type followed by square brackets [] and the variable name.

int[] numbers;  // Declares an array of integers

Initialization: You can initialize an array by specifying its size or providing values at the time of declaration.

Method 1: Using new keyword with size

int[] numbers = new int[5];  // Creates an array to hold 5 integers

Method 2: Directly initializing with values

int[] numbers = {10, 20, 30, 40, 50};  // An array with 5 elements

Note: In Java, arrays are zero-indexed, meaning the first element is at index 0 and the last element is at index size-1.


3. Accessing Array Elements

You can access individual elements in an array using their index.

Example:

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

// Access the first element
System.out.println("First element: " + numbers[0]);  // Output: 10

// Access the third element
System.out.println("Third element: " + numbers[2]);  // Output: 30

Modifying Array Elements: You can change the value of a specific element in an array using its index.

numbers[1] = 25;  // Changes the second element from 20 to 25

4. Length of an Array

Java arrays have a built-in property called length that gives the total number of elements in the array.

Example:

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

// Get the length of the array
System.out.println("Array length: " + numbers.length);  // Output: 5

Important Points:

  • The length property returns the size of the array, but remember that valid index values range from 0 to length - 1.

5. Looping Through Arrays

Arrays can be traversed using loops. The most common loop for arrays is the for loop, but enhanced for loops (also known as the for-each loop) can also be used.

Using a for loop:

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

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

Using an enhanced for-each loop: The enhanced for loop is simpler and is used to iterate over arrays without needing an index.

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

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

6. Multidimensional Arrays

Java supports multidimensional arrays, which are essentially arrays of arrays. The most common multidimensional array is the 2D array.

NOTE : We must have to specify row numbers , whereas column numbers are not compulsory to specify.

Declaring and Initializing a 2D Array:

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

In this example, matrix is a 2D array with 3 rows and 3 columns.

Accessing Elements in a 2D Array:

System.out.println(matrix[0][0]);  // Output: 1
System.out.println(matrix[1][2]);  // Output: 6

Traversing a 2D Array: You can use nested for loops to iterate over each element of a 2D array.

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

7. Arrays of Objects

In Java, arrays can store not only primitive data types but also objects. For example, you can create an array of strings or even custom objects.

Array of Strings:

String[] names = {"Alice", "Bob", "Charlie"};

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

Array of Objects:

class Student {
    String name;
    int age;

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

public class Main {
    public static void main(String[] args) {
        Student[] students = {
            new Student("Alice", 20),
            new Student("Bob", 22),
            new Student("Charlie", 19)
        };

        for (Student student : students) {
            System.out.println(student.name + " is " + student.age + " years old.");
        }
    }
}

8. Practical Example: Array-Based Shopping Cart

Here's a practical example where arrays can be used to implement a simple shopping cart system.

Example:

import java.util.Scanner;

public class ShoppingCart {
    public static void main(String[] args) {
        String[] products = {"Apple", "Banana", "Orange", "Grapes"};
        int[] quantities = new int[products.length];
        Scanner scanner = new Scanner(System.in);

        // Ask the user for quantities
        for (int i = 0; i < products.length; i++) {
            System.out.print("Enter quantity for " + products[i] + ": ");
            quantities[i] = scanner.nextInt();
        }

        // Display the cart summary
        System.out.println("Shopping Cart Summary:");
        for (int i = 0; i < products.length; i++) {
            System.out.println(products[i] + ": " + quantities[i] + " units");
        }

        scanner.close();
    }
}

How it Works:

  • The program stores a list of products in an array.

  • It asks the user to input the quantity for each product, which is then stored in another array.

  • Finally, it prints out a summary of the shopping cart.


Summary of Day 4

By the end of Day 4, we will have a comprehensive understanding of:

  • Declaring, initializing, and accessing arrays in Java.

  • Working with both single-dimensional and multidimensional arrays.

  • Using loops to traverse arrays.

  • Practical use cases for arrays, such as building a shopping cart.

Arrays are fundamental to programming in Java, and mastering them sets a strong foundation for understanding more advanced data structures. For further advanced topics in java , Stay tuned!.

More from this blog

Mohit's blog

51 posts