4.4 Lab - Arrays in Java

Introduction

In this lab, you will learn how to work with arrays in Java. An array is a data structure that allows you to store multiple values of the same data type in a single variable. Arrays are useful for managing collections of data such as lists of numbers, names, or other objects. You will create, initialize, and manipulate arrays in this lab, exploring how to work with both single-dimensional and multi-dimensional arrays.

Objectives

By the end of this lab, you will be able to:

  1. Understand and declare arrays in Java.
  2. Initialize arrays with values.
  3. Access and modify elements within an array.
  4. Use loops to iterate through an array.
  5. Work with multi-dimensional arrays.

Lab Steps

Step 1: Access the Linux Terminal
  1. Open the terminal on your Linux system.
  2. Ensure you are in your home directory by running the command:
    cd ~
    
Step 2: Create and Edit a Java File
  1. Create a new Java file using Nano called ArrayExample.java:
    nano ArrayExample.java
    
  2. Type the following Java code into the file. This program will demonstrate how to declare, initialize, and access elements in an array:
    public class ArrayExample {
        public static void main(String[] args) {
            // Declare an array of integers
            int[] numbers = {1, 2, 3, 4, 5};
    
            // Access and print elements of the array
            System.out.println("First element: " + numbers[0]);
            System.out.println("Second element: " + numbers[1]);
            System.out.println("Third element: " + numbers[2]);
    
            // Modify an element in the array
            numbers[2] = 10;
            System.out.println("Updated third element: " + numbers[2]);
    
            // Use a for loop to iterate over the array
            System.out.println("\nAll elements in the array:");
            for (int i = 0; i < numbers.length; i++) {
                System.out.println(numbers[i]);
            }
        }
    }
    
  3. Save the file by pressing CTRL + O, then hit Enter to confirm the filename.
  4. Exit Nano by pressing CTRL + X.
Step 3: Compile the Java Program
  1. In the terminal, compile the Java program using the javac command:
    javac ArrayExample.java
    
  2. If there are no errors, this command will create a file named ArrayExample.class. Verify this by running:
    ls
    
Step 4: Run the Java Program
  1. Run the compiled program using the java command:
    java ArrayExample
    
  2. The program will display the elements of the array, similar to the following output:
    First element: 1
    Second element: 2
    Third element: 3
    Updated third element: 10
    
    All elements in the array:
    1
    2
    10
    4
    5
    
Step 5: Modify the Program to Use User Input
  1. Open the ArrayExample.java file again using Nano:
    nano ArrayExample.java
    
  2. Modify the program to ask the user for 5 numbers and store them in the array. Add the following lines to take user input:
    import java.util.Scanner;
    
    public class ArrayExample {
        public static void main(String[] args) {
            Scanner scanner = new Scanner(System.in);
            
            // Create an array of 5 integers
            int[] numbers = new int[5];
    
            // Get user input to fill the array
            System.out.println("Enter 5 numbers:");
            for (int i = 0; i < numbers.length; i++) {
                System.out.print("Number " + (i+1) + ": ");
                numbers[i] = scanner.nextInt();
            }
    
            // Print the array elements
            System.out.println("\nYou entered:");
            for (int i = 0; i < numbers.length; i++) {
                System.out.println(numbers[i]);
            }
        }
    }
    
  3. Save, exit, recompile, and run the program again to see the updated behavior. The program will now prompt for 5 numbers and display them:
    javac ArrayExample.java
    java ArrayExample
    
Step 6: Work with Multi-Dimensional Arrays
  1. Modify the program to add a 2D array (multi-dimensional array) and print its elements. For example:
    // Create a 2D array
    int[][] matrix = {
        {1, 2, 3},
        {4, 5, 6},
        {7, 8, 9}
    };
    
    // Print elements of the 2D array
    System.out.println("\n2D Array (Matrix):");
    for (int i = 0; i < matrix.length; i++) {
        for (int j = 0; j < matrix[i].length; j++) {
            System.out.print(matrix[i][j] + " ");
        }
        System.out.println();
    }
    
  2. Save, exit, recompile, and run the program to see how the 2D array is printed:
    javac ArrayExample.java
    java ArrayExample
    
Step 7: Experiment with Array Methods (Optional)
  1. Modify the program to explore other array-related operations, such as finding the maximum or minimum value in the array:
    // Find the maximum value in the array
    int max = numbers[0];
    for (int i = 1; i < numbers.length; i++) {
        if (numbers[i] > max) {
            max = numbers[i];
        }
    }
    System.out.println("\nMaximum value in the array: " + max);
    
  2. Save, exit, recompile, and run the program. It will now display the maximum value in the array.
Step 8: Cleanup (Optional)
  1. Once you're done, clean up the directory by removing the .class files:
    rm *.class
    

Summary

In this lab, you learned how to create, initialize, and manipulate arrays in Java. You explored both single-dimensional and multi-dimensional arrays, accessed and modified array elements, and used loops to iterate through arrays. Arrays are a powerful way to store and manage multiple values in a program, making them a fundamental tool in any developer's toolkit.