Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iterating over an Array

I tried this block of code and it yields two different results

public class PassArrayToFunction {
    public static void increase1(int[] arr){
        for(int a: arr)
            a += 1;
    }
    public static void increase2(int[] arr){
        for(int i=0;i<arr.length;i++)
            arr[i]++;
    }
    public static void main(String[] args) {
        int arr[] = {1,2,3};
        increase1(arr);
        System.out.println(Arrays.toString(arr));
        increase2(arr);
        System.out.println(Arrays.toString(arr));
    }
}

The result:

So is there any underlying difference between 2 ways to iterating an array because principle wise it's basically the same

I was expecting sbd to clarify passing array to function in JAVA

like image 889
Cường Avatar asked Apr 18 '26 16:04

Cường


2 Answers

The key difference is how the two loops work with the array elements:

increase1

The enhanced for-loop (for(int a : arr)) assigns the value of each array element to the variable a. Since a is a copy of the value (not a reference to the actual array element), doing a += 1 only modifies the copy, leaving the original array unchanged.

increase 2

The traditional for-loop uses an index to access each element directly (arr[i]). When you increment arr[i] with arr[i]++, you’re modifying the actual element in the array.


Therefore, after calling increase1(arr), the array remains [1, 2, 3], while after calling increase2(arr), the array becomes [2, 3, 4].

like image 169
Brandon Stillitano Avatar answered Apr 21 '26 05:04

Brandon Stillitano


They are not the same at all.

In the first function you operate on a copy of the values in the array, in the second one you manipulate the actual values.

If you manipulate ad array of ints (primitive type) the increase1 function operates on a copy of the values of the array and the changes are lost when the iteration pass on the next index of the array.

When you operate on complex types, you work on a reference and then you do not see any difference between increase1 and increase2 function behaviour.

see: What does for(int i : x) do?

like image 20
Eineki Avatar answered Apr 21 '26 06:04

Eineki