Arrays in Java

1. Traversing Array Elements

1.1 Traversing an Array: Display the elements of the array
  1. Standard for loop traversal: Access array elements using indexes
  2. Enhanced for loop: for (data_type variable : array_name)

Distinction:

  • Use standard for loop when index is needed, use enhanced for loop otherwise
  • Enhanced for loop is based on standard for loop internally
public class Travesal1 {
    public static void main(String[] args) {
        String[] sArr = {"Anqila", "Daji", "Lvbu"};
        // Enhanced for loop
        for (String e : sArr) {
            System.out.println("e = " + e);
        }

        // Standard for loop
        for (int index = 0; index < sArr.length; index++) {
            String ele = sArr[index];
            System.out.println("ele = " + ele);
        }
    }
}

class Travesal02 {
    public static void main(String[] args) {
        int[] arr = {30, 20, 40, 50, 90, 80};
        // Enhanced for loop
        for (int i : arr) {
            System.out.println("Enhanced for= " + i);
        }

        // Standard for loop
        for (int e = 0; e < arr.length; e++) {
            System.out.println("Standard for = " + arr[e]);
        }
    }
}
1.2 Define an integer array and calculate the sum
public class TrversalExer2 {
    public static void main(String[] args) {
        int[] arr = {66, 77, 88, 99, 11, 22, 33};
        int sum = 0;
        // Enhanced for loop
        for (int e : arr) {
            sum += e;
        }
        // Standard for loop
        //        for (int i = 0; i < arr.length; i++) {
        //            sum += arr[i];
        //        }
        System.out.println("Total sum: " + sum);
    }
}
1.3 Define an integer array and find the maximum value and its index
public class TrversalExer_1 {
    public static void main(String[] args) {
        int[] arr = {66, 77, 88, 99, 11, 22, 33};
        int maxNum = 0;
        int index = 0;
        for (int i = 0; i < arr.length; i++) {
            if (arr[i] > maxNum) {
                maxNum = arr[i];
                index = i;
            }
        }
        System.out.println("Maximum value: " + maxNum + ", Index: " + index);
    }
}

class TrversalExer_2 {
    public static void main(String[] args) {
        int[] arr = {66, 77, 88, 99, 11, 22, 33};
        int minNum = arr[0];
        int index = 0;
        for (int i = 0; i < arr.length; i++) {
            if (arr[i] < minNum) {
                minNum = arr[i];
                index = i;
            }
        }
        System.out.println("Minimum value: " + minNum + ", Index: " + index);
    }
}

2. Memory Division in Java Virtual Machine

To improve procsesing efficiency, memory is divided into different regions, each with specific data handling and memory management methods.

  1. Stack: Stores local variables within methods
  2. Heap: Objects, including arrays, are stored here
  3. Native Method Stack: Used for calling native code from other languages
  4. Method Area (Metaspace): Stores static information, constants, and class descriptions
  5. Program Counter: Stores the address of the next instruction to be executed
2.1 Drawing Stack and Heap Diagrams
public class JVMMemory3 {
    public static void main(String[] args) {
        int m = 10;
        int[] arr = new int[3];
        arr[0] = 99;
        arr[2] = 66;
        System.out.println("arr[0] = " + arr[0]);
        System.out.println("arr[1] = " + arr[1]);
        System.out.println("arr[3] = " + arr[3]);
    }
}
2.2 Output English Weekdays

Use an array to store the English names of weekdays from Monday to Sunday. Input a number between 1-7 to display the corresponding name.

public class ArrayExer4 {
    public static void main(String[] args) {
        String[] arr = {"Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"};
        Scanner in = new Scanner(System.in);
        System.out.println("Enter a number between 1-7:");
        int month = in.nextInt();
        String message = arr[month - 1];
        System.out.println("message = " + message);
        in.close();
    }
}
2.3 Read Student Scores from Keyboard, Find the Highest Score, and Output the Grade
class ArrayExery_2 {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        System.out.println("Enter the number of students:");
        int count = in.nextInt();
        int[] arr = new int[count];
        for (int i = 0; i < arr.length; i++) {
            System.out.println("Enter the score of student " + (i + 1));
            int source = in.nextInt();
            arr[i] = source;
        }
        int maxScore = arr[0];
        for (int i : arr) {
            if (i > maxScore) {
                maxScore = i;
            }
        }
        System.out.println("maxScore = " + maxScore);
        for (int i = 0; i < arr.length; i++) {
            int score = arr[i];
            if (score >= maxScore - 10) {
                System.out.println("Student " + (i + 1) + " grade is: A");
            } else if (score >= maxScore - 20) {
                System.out.println("Student " + (i + 1) + " grade is: B");
            } else if (score >= maxScore - 30) {
                System.out.println("Student " + (i + 1) + " grade is: C");
            } else {
                System.out.println("Student " + (i + 1) + " grade is: D");
            }
        }
        in.close();
    }
}

3. Bubble Sort

3.1 Preparation for Bubble Sort
public class BubbleSort5 {
    public static void main(String[] args) {
        int m = 20;
        int n = 10;
        System.out.println("Before swap: m = " + m + ", n = " + n);
        int temp = m;
        m = n;
        n = temp;
        System.out.println("After swap: m = " + m + ", n = " + n);
        int[] arr = {77, 66, 55, 44, 33, 22, 11};
        System.out.println("arr = " + arr);
        System.out.println("Arrays.toString(arr) = " + Arrays.toString(arr));
    }
}
3.2 Basic Implementation of Bubble Sort
class BubbleSort_1 {
    public static void main(String[] args) {
        int[] arr = {77, 66, 55, 44, 33, 22, 11};
        System.out.println("Before sorting = " + Arrays.toString(arr));
        for (int i = 0; i < arr.length - 1; i++) {
            for (int j = 0; j < arr.length - 1; j++) {
                if (arr[j] > arr[j + 1]) {
                    int temp = arr[j];
                    arr[j] = arr[j + 1];
                    arr[j + 1] = temp;
                }
            }
            System.out.println("Sorting = " + Arrays.toString(arr));
        }
        System.out.println("After sorting = " + Arrays.toString(arr));
    }
}
3.3 Optimized Bubble Sort
class BubbleSort_2 {
    public static void main(String[] args) {
        int[] arr = {77, 66, 55, 44, 33, 22, 11};
        System.out.println("Before sorting = " + Arrays.toString(arr));
        for (int i = 0; i < arr.length - 1; i++) {
            boolean flag = true;
            for (int j = 0; j < arr.length - 1 - i; j++) {
                if (arr[j] > arr[j + 1]) {
                    int temp = arr[j];
                    arr[j] = arr[j + 1];
                    arr[j + 1] = temp;
                    flag = false;
                }
            }
            if (flag) {
                break;
            }
            System.out.println("Sorting = " + Arrays.toString(arr));
        }
        System.out.println("After sorting = " + Arrays.toString(arr));
    }
}
3.4 Define an array to store student scores and calculate total and average
3.5 Reverse the elements of an array

10 20 30 40 50 60 70 → 70 60 50 40 30 20 10

3.6 Check if a number exists in the array
import java.util.Scanner;
public class ArrayText {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        System.out.println("How many student scores do you want to store?");
        int count = in.nextInt();
        int[] arr = new int[count];
        for (int i = 0; i < arr.length; i++) {
            System.out.println("Enter the score of student " + (i + 1));
            arr[i] = in.nextInt();
        }
        int maxNum = arr[0], minNum = arr[0], sum = 0;
        for (int e : arr) {
            if (e > maxNum) {
                maxNum = e;
            }
            if (e < minNum) {
                minNum = e;
            }
            sum += e;
        }
        System.out.println("Total score = " + sum + ", Maximum score = " + maxNum + ", Minimum score = " + minNum + ", Average score = " + sum / arr.length);
        in.close();
    }
}

4. Reversing an Array

4.1 Reverse 1 (Create a new array for reversal)
public class Reverse7 {
    public static void main(String[] args) {
        int[] arr = {11, 22, 33, 44, 55, 66, 77};
        System.out.println("Before reverse = " + Arrays.toString(arr));
        int[] newArr = new int[arr.length];
        int index = 0;
        for (int i = arr.length - 1; i >= 0; i--) {
            newArr[index] = arr[i];
            index++;
        }
        arr = newArr;
        System.out.println("After reverse = " + Arrays.toString(arr));
    }
}
4.2 Reverse 2 (Reverse in-place)
class Reverse7_1 {
    public static void main(String[] args) {
        int[] arr = {11, 22, 33, 44, 55, 66, 77};
        System.out.println("Before reverse = " + Arrays.toString(arr));
        for (int i = 0; i < arr.length / 2; i++) {
            int temp = arr[i];
            arr[i] = arr[arr.length - 1 - i];
            arr[arr.length - 1 - i] = temp;
        }
        System.out.println("After reverse = " + Arrays.toString(arr));
    }
}
4.3 Reverse 3 (Two pointers approach)
class Reverse7_3 {
    public static void main(String[] args) {
        int[] arr = {11, 22, 33, 44, 55, 66, 77};
        System.out.println("Before reverse = " + Arrays.toString(arr));
        for (int LIndex = 0, RIndex = arr.length - 1; LIndex < RIndex; LIndex++, RIndex--) {
            int temp = arr[LIndex];
            arr[LIndex] = arr[RIndex];
            arr[RIndex] = temp;
        }
        System.out.println("After reverse = " + Arrays.toString(arr));
    }
}
4.5 Array Element Expansion
4.6 Find all even numbers and calculate their sum
public class EvenTest8 {
    public static void main(String[] args) {
        int[] arr = {10, 11, 12, 13, 14, 15, 16, 17};
        int sum = 0;
        for (int e : arr) {
            if (e % 2 == 0) {
                sum += e;
            }
        }
        System.out.println("sum = " + sum);
    }
}
4.7 Array Expansion (Adding elements to a full array)
class EvenTest8_1 {
    public static void main(String[] args) {
        String[] arr = {"Zhangsan", "Wangwu", "Lisi"};
        String[] newArr = new String[arr.length << 1];
        for (int i = 0; i < arr.length; i++) {
            newArr[i] = arr[i];
        }
        arr = newArr;
        arr[3] = "Anqila";
        System.out.println("Arrays.toString(arr) = " + Arrays.toString(arr));
    }
}

5. Summary

  1. Array element traversal
  2. Memory diagram of array elements
  3. Small algorithms for arrays

6. Initialization of Two-Dimensional Arrays

7. Static Initialization of Two-Dimensional Arrays

Static initialization: Determine the length and content at compile time

Format 1: data_type[][] array_name = {{}, {}};

Format 2: data_type[][] array_name = new data_type[][]{{"Li Bai", "Li San"}, {"Anqila", "Haha", "Xixi"}};

public class DoublearrayTest_1 {
    public static void main(String[] args) {
        int[][] arr = {{20, 40, 60}, {11, 22, 33, 44}, {55, 66, 77, 88, 99}, {100, 200}};
        System.out.println("arr.length = " + arr.length);
        System.out.println("arr[0] = " + arr[0]);
        System.out.println("arr[0][2] = " + arr[0][2]);
        System.out.println("arr[2][4] = " + arr[2][4]);
        System.out.println("arr[3].length = " + arr[3].length);

        String[][] arr1 = new String[][]{{"Li Bai", "Li San"}, {"Anqila", "Haha", "Xixi"}};
        System.out.println("arr1.length = " + arr1.length);
        System.out.println("arr1[1][2] = " + arr1[1][2]);
    }
}

8. Dynamic Initialization of Two-Dimensional Arrays

Dynamic initialization: Determine the length and default values at compile time

Format 1: Regular rectangle data_type[][] array_name = new data_type[array1][array2];

class DoublearrayTest1_2 {
    public static void main(String[] args) {
        int[][] arr = new int[5][6];
        System.out.println("arr.length = " + arr.length);
        System.out.println("arr[0].length = " + arr[0].length);
        System.out.println("arr[4].length = " + arr[4].length);
        System.out.println("arr[0][0] = " + arr[0][0]);
    }
}

Format 2: Irregular rectangle data_type[][] array_name = new data_type[array1][];

class DoublearrayTest1_2 {
    public static void main(String[] args) {
        int[][] iArr = new int[3][];
        System.out.println("iArr[0] = " + iArr[0]);
        iArr[0] = new int[6];
        iArr[0][0] = 66;
        iArr[1] = new int[]{33, 55, 77};
    }
}

9. Traversing Two-Dimensional Arrays

public class Taversal_2 {
    public static void main(String[] args) {
        String[][] arr = {{"Infringement", "Wang Wu"}, {"Hmm", "Make", "Headache"}, {"Shift Right", "Haha", "Change", "Get"}};
        for (String[] eleArr : arr) {
            for (String e : eleArr) {
                System.out.println(e + "\t");
            }
            System.out.println();
        }
    }
}

class Taversal2_1 {
    public static void main(String[] args) {
        int[][] arr = {{11, 22}, {33, 44, 55}};
        for (int[] eleArr : arr) {
            for (int e : eleArr) {
                System.out.println(e + "\t");
            }
        }
    }
}

10. Memory Diagram of Two-Dimensional Arrays

Elements of two-dimensional arrays are one-dimensional arrays. If not a primitive type, it's a reference type, which defaults to null.

11. Finding the Maximum and Minimum Values in a Two-Dimensional Array

public class BoubleArrayExer_3 {
    public static void main(String[] args) {
        int[][] arr = {{111, 222, 333}, {10, 20, 30}, {-1, -2, 99}};
        int maxNum = arr[0][0];
        int minNum = arr[0][0];
        for (int[] eleArr : arr) {
            for (int e : eleArr) {
                if (e > maxNum) {
                    maxNum = e;
                }
                if (e < minNum) {
                    minNum = e;
                }
            }
        }
        System.out.println("Maximum value = " + maxNum + ", Minimum value = " + minNum);
    }
}

Input a positive integer, dynamically create a two-dimensional array of that length, and traverse it to print to the console.

class BoubleArrayExer3_1 {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        System.out.println("Enter the array length:");
        int length = in.nextInt();
        int[][] arr = new int[length][];
        for (int i = 0; i < arr.length; i++) {
            arr[i] = new int[i + 1];
            for (int j = 0; j < arr[i].length; j++) {
                arr[i][j] = i + 1;
            }
        }
        for (int[] eleArr : arr) {
            for (int e : eleArr) {
                System.out.print(e);
            }
            System.out.println();
        }
        in.close();
    }
}

Tags: java Arrays loops Memory Management bubble sort

Posted on Thu, 21 May 2026 16:42:57 +0000 by sharp.mac