2

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

2
  • in your second loop you must do something like int a = a[i]; a += 1; to have the equivalent of first loop (obviously? incrementing a will not be reflected in the array [both cases]) Commented Feb 22 at 13:22
  • In such cases, I recommend that you start the code in debug mode. You can then always set breakpoints in your two functions and observe how "a" and "arr" change. Or how they don't change ;) Commented Feb 25 at 14:07

4 Answers 4

9

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].

Sign up to request clarification or add additional context in comments.

Comments

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?

Comments

1

Let's see your code:

        for(int a: arr)
            a += 1;

When it says int a, it basically says that I create a local variable called a that will represent the current element of the arr array that is currently being looped which is logically almost the same as

for (int i = 0; i < arr.length; i++) {
    int a = arr[i];
    a++;
}

as it also creates a copy of the array element and increments the copy, but not the original. Your

        for(int i=0;i<arr.length;i++)
            arr[i]++;

uses an index to actually refer the array elements, loops incrementing this index and in each step it increments the actual array element, not some copy of it.

Comments

0

For-each loop (for(int a: arr)) does not modify the original array because a is just a copy of each element.

Traditional loop (for(int i=0; i<arr.length; i++)) modifies the original array since it accesses the actual indices.

5 Comments

not really relevant which loop is used; more like the difference between changing a local variable and changing an array element (if you change an array element inside an enhanced loop [aka for-each loop], it will still change the element [just a bit harder, illogical, to access the array element inside such a loop])
@user85421 that's what Senin was meaning if I'm not mistaken.
@Lajos - I see, it's just a strange way to emphasize something to indicate it is not relevant :-/
@user85421 yes, indeed. It's the language barrier. I do feel for people affected by it, because for quite a while my English was direct translation from my language, oftentimes accidentally saying things in a confusing manner. It happens to anyone not yet having a firm command on the language they use.
@Lapos - trying to correct this, is also part of the reason for posting my first comment - (apparently) not everybody is able to recognize the intended meaning of this answer

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.