How to edit a specific element in an array in Java?

To modify a certain element in an array, you can access and change the specific position in the array using an index.

The following is an example code that demonstrates how to modify a specific element in an array.

public class Main {
    public static void main(String[] args) {
        // 声明和初始化一个整数数组
        int[] arr = {1, 2, 3, 4, 5};

        // 输出原始数组
        System.out.println("原始数组:");
        for (int i = 0; i < arr.length; i++) {
            System.out.print(arr[i] + " ");
        }
        System.out.println();

        // 修改数组中的第三个元素为10
        arr[2] = 10;

        // 输出修改后的数组
        System.out.println("修改后的数组:");
        for (int i = 0; i < arr.length; i++) {
            System.out.print(arr[i] + " ");
        }
        System.out.println();
    }
}

Output results:

原始数组:
1 2 3 4 5 
修改后的数组:
1 2 10 4 5

In the example above, we defined an integer array arr and initialized it as {1, 2, 3, 4, 5}. Then, we used index 2 to access the third element in the array and changed it to 10. Finally, we iterated through the array using a loop and printed out each modified array element one by one.

bannerAds