如何创建固定大小的 Java 数组

JavaJavaBeginner
立即练习

💡 本教程由 AI 辅助翻译自英文原版。如需查看原文,您可以 切换至英文原版

Introduction

This tutorial explores the essential techniques for creating and using fixed-size arrays in Java. Arrays are fundamental data structures that allow you to store multiple elements of the same type in a single variable. By mastering Java arrays, you will gain a crucial programming skill that serves as a foundation for more advanced topics.

In this lab, you will learn how to declare, initialize, and manipulate arrays through hands-on practice. Each step builds upon the previous one, providing you with a comprehensive understanding of array operations in Java.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL java(("Java")) -.-> java/BasicSyntaxGroup(["Basic Syntax"]) java(("Java")) -.-> java/DataStructuresGroup(["Data Structures"]) java/BasicSyntaxGroup -.-> java/data_types("Data Types") java/BasicSyntaxGroup -.-> java/if_else("If...Else") java/BasicSyntaxGroup -.-> java/for_loop("For Loop") java/DataStructuresGroup -.-> java/arrays("Arrays") java/DataStructuresGroup -.-> java/arrays_methods("Arrays Methods") subgraph Lab Skills java/data_types -.-> lab-418028{{"如何创建固定大小的 Java 数组"}} java/if_else -.-> lab-418028{{"如何创建固定大小的 Java 数组"}} java/for_loop -.-> lab-418028{{"如何创建固定大小的 Java 数组"}} java/arrays -.-> lab-418028{{"如何创建固定大小的 Java 数组"}} java/arrays_methods -.-> lab-418028{{"如何创建固定大小的 Java 数组"}} end

Creating Your First Java Array

Arrays in Java are objects that store multiple variables of the same type. Unlike some other data structures, once an array is created, its size cannot be changed. This makes arrays particularly efficient for storing a predetermined number of elements.

Array Declaration and Initialization

Arrays can be created in different ways. Let's explore the most common methods.

Creating a Simple Integer Array

First, let's create a new Java file in our project directory. In the WebIDE, click on the File menu, select "New File," and name it ArrayDemo.java.

Add the following code to your file:

public class ArrayDemo {
    public static void main(String[] args) {
        // Method 1: Declare and initialize an array separately
        int[] numbers;       // Array declaration
        numbers = new int[5]; // Array initialization with size 5

        // Default values are assigned (all zeros for int array)
        System.out.println("Array elements after initialization:");
        for (int i = 0; i < numbers.length; i++) {
            System.out.println("numbers[" + i + "] = " + numbers[i]);
        }

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

To compile and run your Java program, open a terminal in the WebIDE (if not already open) and execute the following commands:

javac ArrayDemo.java
java ArrayDemo

You should see output similar to this:

Array elements after initialization:
numbers[0] = 0
numbers[1] = 0
numbers[2] = 0
numbers[3] = 0
numbers[4] = 0

Array length: 5

As you can see, Java automatically initializes all elements in an integer array to zero.

Array Initialization with Values

Now, let's modify our ArrayDemo.java file to include another way of creating arrays - initialization with specific values:

public class ArrayDemo {
    public static void main(String[] args) {
        // Method 1: Declare and initialize an array separately
        int[] numbers;       // Array declaration
        numbers = new int[5]; // Array initialization with size 5

        // Default values are assigned (all zeros for int array)
        System.out.println("Array elements after initialization:");
        for (int i = 0; i < numbers.length; i++) {
            System.out.println("numbers[" + i + "] = " + numbers[i]);
        }

        System.out.println("\nArray length: " + numbers.length);

        // Method 2: Initialize with specific values
        int[] scores = {85, 90, 75, 88, 92};

        System.out.println("\nScores array elements:");
        for (int i = 0; i < scores.length; i++) {
            System.out.println("scores[" + i + "] = " + scores[i]);
        }
    }
}

Compile and run the updated program:

javac ArrayDemo.java
java ArrayDemo

You should now see additional output:

Array elements after initialization:
numbers[0] = 0
numbers[1] = 0
numbers[2] = 0
numbers[3] = 0
numbers[4] = 0

Array length: 5

Scores array elements:
scores[0] = 85
scores[1] = 90
scores[2] = 75
scores[3] = 88
scores[4] = 92

Creating Arrays of Different Types

Let's create a new file named ArrayTypes.java to demonstrate arrays of different data types. In the WebIDE, create a new file and add the following code:

public class ArrayTypes {
    public static void main(String[] args) {
        // String array
        String[] names = new String[3];
        names[0] = "Alice";
        names[1] = "Bob";
        names[2] = "Charlie";

        System.out.println("String array elements:");
        for (int i = 0; i < names.length; i++) {
            System.out.println("names[" + i + "] = " + names[i]);
        }

        // Double array with initialization
        double[] prices = {19.99, 29.99, 15.50, 99.99};

        System.out.println("\nDouble array elements:");
        for (int i = 0; i < prices.length; i++) {
            System.out.println("prices[" + i + "] = " + prices[i]);
        }

        // Boolean array
        boolean[] flags = new boolean[3];
        flags[0] = true;

        System.out.println("\nBoolean array elements:");
        for (int i = 0; i < flags.length; i++) {
            System.out.println("flags[" + i + "] = " + flags[i]);
        }
    }
}

Compile and run this program:

javac ArrayTypes.java
java ArrayTypes

You will see the following output:

String array elements:
names[0] = Alice
names[1] = Bob
names[2] = Charlie

Double array elements:
prices[0] = 19.99
prices[1] = 29.99
prices[2] = 15.5
prices[3] = 99.99

Boolean array elements:
flags[0] = true
flags[1] = false
flags[2] = false

Notice that different data types have different default values:

  • Numeric types (int, double, etc.) default to zero
  • Boolean defaults to false
  • Reference types (String, objects) default to null

This step has shown you the basics of creating arrays in Java. You've learned how to declare arrays, initialize them with and without values, and create arrays of different data types.

Working with Array Elements

Now that we know how to create arrays, let's explore how to work with array elements. This includes setting values, accessing elements, and modifying array contents.

Accessing and Modifying Array Elements

Create a new file named ArrayOperations.java in your WebIDE with the following code:

public class ArrayOperations {
    public static void main(String[] args) {
        // Create an integer array
        int[] numbers = new int[5];

        // Assign values to array elements
        numbers[0] = 10;
        numbers[1] = 20;
        numbers[2] = 30;
        numbers[3] = 40;
        numbers[4] = 50;

        // Display the original array
        System.out.println("Original array elements:");
        for (int i = 0; i < numbers.length; i++) {
            System.out.println("numbers[" + i + "] = " + numbers[i]);
        }

        // Access specific elements
        int firstElement = numbers[0];
        int thirdElement = numbers[2];

        System.out.println("\nAccessing specific elements:");
        System.out.println("First element: " + firstElement);
        System.out.println("Third element: " + thirdElement);

        // Modify array elements
        numbers[1] = 25;    // Change second element
        numbers[4] = 55;    // Change last element

        // Display the modified array
        System.out.println("\nArray after modification:");
        for (int i = 0; i < numbers.length; i++) {
            System.out.println("numbers[" + i + "] = " + numbers[i]);
        }
    }
}

Compile and run this program:

javac ArrayOperations.java
java ArrayOperations

You should see this output:

Original array elements:
numbers[0] = 10
numbers[1] = 20
numbers[2] = 30
numbers[3] = 40
numbers[4] = 50

Accessing specific elements:
First element: 10
Third element: 30

Array after modification:
numbers[0] = 10
numbers[1] = 25
numbers[2] = 30
numbers[3] = 40
numbers[4] = 55

Array Boundaries and Exception Handling

When working with arrays, it's crucial to understand array boundaries. Java arrays have a fixed size, and trying to access an element outside these boundaries will cause an exception.

Create a new file named ArrayBoundaries.java with the following code:

public class ArrayBoundaries {
    public static void main(String[] args) {
        int[] numbers = new int[3];  // Array with 3 elements (indices 0, 1, 2)

        // Set values within boundaries
        numbers[0] = 10;
        numbers[1] = 20;
        numbers[2] = 30;

        System.out.println("Array elements within boundaries:");
        for (int i = 0; i < numbers.length; i++) {
            System.out.println("numbers[" + i + "] = " + numbers[i]);
        }

        // Demonstrating boundary checking with try-catch
        System.out.println("\nAttempting to access elements outside boundaries:");

        try {
            // This is valid
            System.out.println("Accessing numbers[2]: " + numbers[2]);

            // This will cause an ArrayIndexOutOfBoundsException
            System.out.println("Attempting to access numbers[3]: " + numbers[3]);
        } catch (ArrayIndexOutOfBoundsException e) {
            System.out.println("Error: " + e.getMessage());
            System.out.println("Cannot access an index outside the array bounds (0 to " + (numbers.length-1) + ")");
        }
    }
}

Compile and run this program:

javac ArrayBoundaries.java
java ArrayBoundaries

You should see output like this:

Array elements within boundaries:
numbers[0] = 10
numbers[1] = 20
numbers[2] = 30

Attempting to access elements outside boundaries:
Accessing numbers[2]: 30
Error: Index 3 out of bounds for length 3
Cannot access an index outside the array bounds (0 to 2)

This demonstrates that Java performs bounds checking on arrays. Attempting to access numbers[3] throws an exception because the array only has elements at indices 0, 1, and 2.

Calculating and Storing Values in Arrays

Let's create a practical example where we calculate values and store them in an array. Create a file named TemperatureConverter.java:

public class TemperatureConverter {
    public static void main(String[] args) {
        // Array to store Celsius temperatures
        double[] celsiusTemps = {0, 10, 20, 30, 40};

        // Array to store converted Fahrenheit temperatures
        double[] fahrenheitTemps = new double[celsiusTemps.length];

        // Convert each Celsius temperature to Fahrenheit
        for (int i = 0; i < celsiusTemps.length; i++) {
            // Formula: F = C * 9/5 + 32
            fahrenheitTemps[i] = celsiusTemps[i] * 9/5 + 32;
        }

        // Display the conversion table
        System.out.println("Temperature Conversion Table:");
        System.out.println("---------------------------");
        System.out.println("Celsius    |    Fahrenheit");
        System.out.println("---------------------------");

        for (int i = 0; i < celsiusTemps.length; i++) {
            System.out.printf("%-10.1f |    %-10.1f\n",
                             celsiusTemps[i],
                             fahrenheitTemps[i]);
        }
    }
}

Compile and run this program:

javac TemperatureConverter.java
java TemperatureConverter

The output will be a temperature conversion table:

Temperature Conversion Table:
---------------------------
Celsius    |    Fahrenheit
---------------------------
0.0        |    32.0
10.0       |    50.0
20.0       |    68.0
30.0       |    86.0
40.0       |    104.0

This example demonstrates how arrays can be used to store related data and perform calculations on multiple values efficiently.

In this step, you've learned how to access and modify array elements, handle array boundaries, and use arrays for practical calculations. These skills form the foundation for more complex array operations.

Advanced Array Operations

Now that you understand the basics of arrays, let's explore more sophisticated operations including array iteration, searching, and using arrays with methods.

Array Iteration Techniques

Java provides multiple ways to iterate through array elements. Create a new file named ArrayIteration.java with the following code:

public class ArrayIteration {
    public static void main(String[] args) {
        // Create a sample array
        String[] fruits = {"Apple", "Banana", "Cherry", "Date", "Elderberry"};

        System.out.println("Array Iteration Methods:");

        // Method 1: Standard for loop
        System.out.println("\n1. Using standard for loop:");
        for (int i = 0; i < fruits.length; i++) {
            System.out.println("fruits[" + i + "] = " + fruits[i]);
        }

        // Method 2: Enhanced for loop (foreach)
        System.out.println("\n2. Using enhanced for loop (foreach):");
        for (String fruit : fruits) {
            System.out.println(fruit);
        }

        // Method 3: While loop
        System.out.println("\n3. Using while loop:");
        int index = 0;
        while (index < fruits.length) {
            System.out.println("fruits[" + index + "] = " + fruits[index]);
            index++;
        }
    }
}

Compile and run this program:

javac ArrayIteration.java
java ArrayIteration

You should see this output:

Array Iteration Methods:

1. Using standard for loop:
fruits[0] = Apple
fruits[1] = Banana
fruits[2] = Cherry
fruits[3] = Date
fruits[4] = Elderberry

2. Using enhanced for loop (foreach):
Apple
Banana
Cherry
Date
Elderberry

3. Using while loop:
fruits[0] = Apple
fruits[1] = Banana
fruits[2] = Cherry
fruits[3] = Date
fruits[4] = Elderberry

Each iteration method has its advantages:

  • Standard for loop: Provides access to array indices and elements
  • Enhanced for loop: Cleaner syntax when you only need the elements
  • While loop: Useful when the iteration condition is more complex

Searching for Elements in an Array

Let's create a program that searches for elements in an array. Create a file named ArraySearch.java:

public class ArraySearch {
    public static void main(String[] args) {
        // Create an array of numbers
        int[] numbers = {10, 25, 33, 47, 52, 68, 79};

        // Values to search for
        int[] searchValues = {33, 50, 79};

        for (int valueToFind : searchValues) {
            boolean found = false;
            int position = -1;

            // Search through the array
            for (int i = 0; i < numbers.length; i++) {
                if (numbers[i] == valueToFind) {
                    found = true;
                    position = i;
                    break;  // Exit the loop once found
                }
            }

            // Display result
            if (found) {
                System.out.println(valueToFind + " found at position " + position);
            } else {
                System.out.println(valueToFind + " not found in the array");
            }
        }
    }
}

Compile and run this program:

javac ArraySearch.java
java ArraySearch

You should see output like this:

33 found at position 2
50 not found in the array
79 found at position 6

This demonstrates a basic linear search algorithm, checking each element until the target value is found or the array is exhausted.

Passing Arrays to Methods

Arrays can be passed to methods just like any other variable. Create a file named ArrayMethods.java:

public class ArrayMethods {
    public static void main(String[] args) {
        // Create an array
        int[] values = {5, 10, 15, 20, 25};

        // Display the original array
        System.out.println("Original array:");
        displayArray(values);

        // Calculate and display the sum
        int sum = calculateSum(values);
        System.out.println("\nSum of all elements: " + sum);

        // Calculate and display the average
        double average = calculateAverage(values);
        System.out.println("Average of all elements: " + average);

        // Double all values in the array
        doubleValues(values);

        // Display the modified array
        System.out.println("\nArray after doubling all values:");
        displayArray(values);
    }

    // Method to display an array
    public static void displayArray(int[] arr) {
        for (int i = 0; i < arr.length; i++) {
            System.out.print(arr[i] + " ");
        }
        System.out.println();
    }

    // Method to calculate the sum of array elements
    public static int calculateSum(int[] arr) {
        int sum = 0;
        for (int value : arr) {
            sum += value;
        }
        return sum;
    }

    // Method to calculate the average of array elements
    public static double calculateAverage(int[] arr) {
        int sum = calculateSum(arr);
        return (double) sum / arr.length;
    }

    // Method to double all values in the array
    public static void doubleValues(int[] arr) {
        for (int i = 0; i < arr.length; i++) {
            arr[i] = arr[i] * 2;
        }
    }
}

Compile and run this program:

javac ArrayMethods.java
java ArrayMethods

You should see output like this:

Original array:
5 10 15 20 25

Sum of all elements: 75
Average of all elements: 15.0

Array after doubling all values:
10 20 30 40 50

This example demonstrates several important concepts:

  1. Arrays can be passed to methods as parameters
  2. Methods can return values calculated from arrays
  3. Changes made to array elements inside a method are reflected outside the method (arrays are passed by reference)

Finding Maximum and Minimum Values

Let's create a program to find the maximum and minimum values in an array. Create a file named ArrayMinMax.java:

public class ArrayMinMax {
    public static void main(String[] args) {
        // Create an array of numbers
        int[] numbers = {42, 17, 88, 23, 56, 9, 71, 33};

        // Find minimum and maximum values
        int min = findMinimum(numbers);
        int max = findMaximum(numbers);

        // Display the array
        System.out.print("Array values: ");
        for (int num : numbers) {
            System.out.print(num + " ");
        }
        System.out.println();

        // Display results
        System.out.println("Minimum value: " + min);
        System.out.println("Maximum value: " + max);
    }

    // Method to find the minimum value in an array
    public static int findMinimum(int[] arr) {
        // Start with the first element as the minimum
        int min = arr[0];

        // Compare with other elements
        for (int i = 1; i < arr.length; i++) {
            if (arr[i] < min) {
                min = arr[i];
            }
        }

        return min;
    }

    // Method to find the maximum value in an array
    public static int findMaximum(int[] arr) {
        // Start with the first element as the maximum
        int max = arr[0];

        // Compare with other elements
        for (int i = 1; i < arr.length; i++) {
            if (arr[i] > max) {
                max = arr[i];
            }
        }

        return max;
    }
}

Compile and run this program:

javac ArrayMinMax.java
java ArrayMinMax

You should see output like this:

Array values: 42 17 88 23 56 9 71 33
Minimum value: 9
Maximum value: 88

In this step, you've learned several advanced array operations including different iteration techniques, searching for elements, passing arrays to methods, and finding minimum and maximum values. These skills will help you work more effectively with arrays in your Java programs.

Practical Array Applications

In this final step, we'll explore practical applications of arrays through a complete example. We'll create a simple grade management system that demonstrates how arrays can be used in real-world programming scenarios.

Creating a Student Grade Tracker

Let's build a program that manages student grades. This program will:

  1. Store student names and their grades
  2. Calculate the average grade
  3. Find the highest and lowest grades
  4. Determine how many students scored above average

Create a new file named GradeTracker.java in your WebIDE:

public class GradeTracker {
    public static void main(String[] args) {
        // Arrays to store student information
        String[] studentNames = {"Alice", "Bob", "Charlie", "David", "Emma",
                                "Frank", "Grace", "Hannah", "Ian", "Julia"};

        int[] studentGrades = {85, 92, 78, 65, 88, 72, 95, 83, 79, 91};

        // Display all student records
        System.out.println("Student Grade Records:");
        System.out.println("---------------------");
        System.out.println("Name\t\tGrade");
        System.out.println("---------------------");

        for (int i = 0; i < studentNames.length; i++) {
            // Add extra tab for short names to align columns
            String tab = studentNames[i].length() <= 5 ? "\t\t" : "\t";
            System.out.println(studentNames[i] + tab + studentGrades[i]);
        }

        // Calculate statistics
        int sum = 0;
        int highest = studentGrades[0];
        int lowest = studentGrades[0];
        String highestStudent = studentNames[0];
        String lowestStudent = studentNames[0];

        for (int i = 0; i < studentGrades.length; i++) {
            // Add to sum for average calculation
            sum += studentGrades[i];

            // Check for highest grade
            if (studentGrades[i] > highest) {
                highest = studentGrades[i];
                highestStudent = studentNames[i];
            }

            // Check for lowest grade
            if (studentGrades[i] < lowest) {
                lowest = studentGrades[i];
                lowestStudent = studentNames[i];
            }
        }

        // Calculate average
        double average = (double) sum / studentGrades.length;

        // Count students above average
        int aboveAverageCount = 0;
        for (int grade : studentGrades) {
            if (grade > average) {
                aboveAverageCount++;
            }
        }

        // Display statistics
        System.out.println("\nClass Statistics:");
        System.out.println("----------------");
        System.out.printf("Class Average: %.2f\n", average);
        System.out.println("Highest Grade: " + highest + " (" + highestStudent + ")");
        System.out.println("Lowest Grade: " + lowest + " (" + lowestStudent + ")");
        System.out.println("Number of students above average: " + aboveAverageCount);
    }
}

Compile and run this program:

javac GradeTracker.java
java GradeTracker

You should see output like this:

Student Grade Records:
---------------------
Name		Grade
---------------------
Alice		85
Bob		92
Charlie	78
David		65
Emma		88
Frank		72
Grace		95
Hannah		83
Ian		79
Julia		91

Class Statistics:
----------------
Class Average: 82.80
Highest Grade: 95 (Grace)
Lowest Grade: 65 (David)
Number of students above average: 5

This program demonstrates how arrays can be used to manage related data (student names and grades) and perform calculations on that data.

Adding Grade Categories

Now, let's enhance our grade tracker by adding grade categories. Create a new file named EnhancedGradeTracker.java:

public class EnhancedGradeTracker {
    public static void main(String[] args) {
        // Arrays to store student information
        String[] studentNames = {"Alice", "Bob", "Charlie", "David", "Emma",
                                "Frank", "Grace", "Hannah", "Ian", "Julia"};

        int[] studentGrades = {85, 92, 78, 65, 88, 72, 95, 83, 79, 91};

        // Create arrays to count grades in each category
        int[] gradeCounts = new int[5]; // A, B, C, D, F

        // Display all student records with grade categories
        System.out.println("Student Grade Records:");
        System.out.println("------------------------------");
        System.out.println("Name\t\tScore\tGrade");
        System.out.println("------------------------------");

        for (int i = 0; i < studentNames.length; i++) {
            // Calculate letter grade
            char letterGrade = calculateGrade(studentGrades[i]);

            // Count grades by category
            switch (letterGrade) {
                case 'A': gradeCounts[0]++; break;
                case 'B': gradeCounts[1]++; break;
                case 'C': gradeCounts[2]++; break;
                case 'D': gradeCounts[3]++; break;
                case 'F': gradeCounts[4]++; break;
            }

            // Add extra tab for short names to align columns
            String tab = studentNames[i].length() <= 5 ? "\t\t" : "\t";
            System.out.println(studentNames[i] + tab + studentGrades[i] + "\t" + letterGrade);
        }

        // Calculate statistics
        double average = calculateAverage(studentGrades);

        // Display statistics
        System.out.println("\nClass Statistics:");
        System.out.println("----------------");
        System.out.printf("Class Average: %.2f\n", average);

        // Display grade distribution
        System.out.println("\nGrade Distribution:");
        System.out.println("------------------");
        System.out.println("A: " + displayStars(gradeCounts[0]));
        System.out.println("B: " + displayStars(gradeCounts[1]));
        System.out.println("C: " + displayStars(gradeCounts[2]));
        System.out.println("D: " + displayStars(gradeCounts[3]));
        System.out.println("F: " + displayStars(gradeCounts[4]));
    }

    // Method to calculate the letter grade from a numeric score
    public static char calculateGrade(int score) {
        if (score >= 90) {
            return 'A';
        } else if (score >= 80) {
            return 'B';
        } else if (score >= 70) {
            return 'C';
        } else if (score >= 60) {
            return 'D';
        } else {
            return 'F';
        }
    }

    // Method to calculate the average of an integer array
    public static double calculateAverage(int[] arr) {
        int sum = 0;
        for (int value : arr) {
            sum += value;
        }
        return (double) sum / arr.length;
    }

    // Method to create a string of stars representing a count
    public static String displayStars(int count) {
        StringBuilder stars = new StringBuilder();
        for (int i = 0; i < count; i++) {
            stars.append("*");
        }
        return stars.toString() + " (" + count + ")";
    }
}

Compile and run this program:

javac EnhancedGradeTracker.java
java EnhancedGradeTracker

You should see output like this:

Student Grade Records:
------------------------------
Name		Score	Grade
------------------------------
Alice		85	B
Bob		92	A
Charlie	78	C
David		65	D
Emma		88	B
Frank		72	C
Grace		95	A
Hannah		83	B
Ian		79	C
Julia		91	A

Class Statistics:
----------------
Class Average: 82.80

Grade Distribution:
------------------
A: *** (3)
B: *** (3)
C: *** (3)
D: * (1)
F:  (0)

This enhanced example demonstrates:

  1. Using multiple arrays to store related data
  2. Creating utility methods for calculations and formatting
  3. Counting and categorizing data
  4. Creating a visual representation of array data

Processing Array Data Based on Conditions

For our final example, let's create a program that processes array data based on conditions. Create a file named FilteredGrades.java:

public class FilteredGrades {
    public static void main(String[] args) {
        // Arrays to store student information
        String[] studentNames = {"Alice", "Bob", "Charlie", "David", "Emma",
                                "Frank", "Grace", "Hannah", "Ian", "Julia"};

        int[] studentGrades = {85, 92, 78, 65, 88, 72, 95, 83, 79, 91};

        // Create a threshold for passing
        int passingGrade = 75;

        // Display all student records with pass/fail status
        System.out.println("Student Grade Records:");
        System.out.println("------------------------------");
        System.out.println("Name\t\tScore\tStatus");
        System.out.println("------------------------------");

        // Count passing and failing students
        int passingCount = 0;

        for (int i = 0; i < studentNames.length; i++) {
            String status = (studentGrades[i] >= passingGrade) ? "PASS" : "FAIL";

            // Count passing students
            if (studentGrades[i] >= passingGrade) {
                passingCount++;
            }

            // Add extra tab for short names to align columns
            String tab = studentNames[i].length() <= 5 ? "\t\t" : "\t";
            System.out.println(studentNames[i] + tab + studentGrades[i] + "\t" + status);
        }

        // Create arrays to store only passing students
        String[] passingStudents = new String[passingCount];
        int[] passingScores = new int[passingCount];

        // Fill the passing student arrays
        int index = 0;
        for (int i = 0; i < studentNames.length; i++) {
            if (studentGrades[i] >= passingGrade) {
                passingStudents[index] = studentNames[i];
                passingScores[index] = studentGrades[i];
                index++;
            }
        }

        // Display only passing students
        System.out.println("\nPassing Students (Score >= 75):");
        System.out.println("------------------------------");
        System.out.println("Name\t\tScore");
        System.out.println("------------------------------");

        for (int i = 0; i < passingStudents.length; i++) {
            // Add extra tab for short names to align columns
            String tab = passingStudents[i].length() <= 5 ? "\t\t" : "\t";
            System.out.println(passingStudents[i] + tab + passingScores[i]);
        }

        // Calculate and display statistics
        System.out.println("\nClass Statistics:");
        System.out.println("----------------");
        System.out.println("Total Students: " + studentNames.length);
        System.out.println("Passing: " + passingCount);
        System.out.println("Failing: " + (studentNames.length - passingCount));
        System.out.printf("Pass Rate: %.1f%%\n",
                         (double) passingCount / studentNames.length * 100);
    }
}

Compile and run this program:

javac FilteredGrades.java
java FilteredGrades

You should see output like this:

Student Grade Records:
------------------------------
Name		Score	Status
------------------------------
Alice		85	PASS
Bob		92	PASS
Charlie	78	PASS
David		65	FAIL
Emma		88	PASS
Frank		72	FAIL
Grace		95	PASS
Hannah		83	PASS
Ian		79	PASS
Julia		91	PASS

Passing Students (Score >= 75):
------------------------------
Name		Score
------------------------------
Alice		85
Bob		92
Charlie	78
Emma		88
Grace		95
Hannah		83
Ian		79
Julia		91

Class Statistics:
----------------
Total Students: 10
Passing: 8
Failing: 2
Pass Rate: 80.0%

This example demonstrates:

  1. Using conditional logic with arrays
  2. Creating filtered arrays based on conditions
  3. Calculating statistics from array data
  4. Presenting information in a formatted way

In this step, you've seen how arrays can be applied to solve practical problems. You've learned to manage related data, perform calculations, and create filtered views of array data based on conditions. These skills will serve as a strong foundation for working with arrays in real-world Java applications.

Summary

In this lab, you have explored the essential techniques for creating and working with fixed-size arrays in Java. You learned how to:

  • Declare and initialize arrays of different data types
  • Access and modify array elements while respecting array boundaries
  • Iterate through arrays using different looping techniques
  • Pass arrays to methods and process array data
  • Find minimum and maximum values in arrays
  • Apply arrays to practical problems like grade tracking

Arrays form the foundation of many data structures in Java and are essential for efficient data storage and manipulation. The skills you've developed in this lab will serve as building blocks for more advanced programming concepts like dynamic data structures, algorithms, and object-oriented programming.

Continue practicing with arrays by modifying the examples provided, creating your own array-based applications, and exploring the Java documentation for additional array utilities in the java.util.Arrays class.