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
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].
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?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With