Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java for loop by value or by reference

I figured out a a problem in my Code. First the code:

public class Main {

    /**
     * @param args
     */
    public static void main(String[] args) {
        String[] blablubb = { "a", "b", "c" };

        for(String s : blablubb) {
            s = "over";
        }
        printArray(blablubb);


        for (int i = 0; i < blablubb.length; i++) {
            blablubb[i] = "over";
        }
        printArray(blablubb);

    }

    public static void printArray(String[] arr) {
        for( String s : arr ) {
            System.out.println(s);
        }
    }

}

The output is:

a
b
c
over
over
over

I assumed the first loop would also overwrite the String in the array. So the output would be over in any case. It seems it creates a copy of the value instead creating a reference. I never perceived this. Am I doing it wrong? Is there an option to create a reference instead?

//Edit: Seems like everybody knows about that except me. I'm from C background and doesn't pay enough attention to the term reference which is very different to C. Fortunately it took me just 10 minutes to figure this out (this time).

like image 832
No3x Avatar asked Jul 31 '13 11:07

No3x


3 Answers

This:

for (String s : blablubb) {
     s = "over";
}

Is equal to this:

for (int i = 0; i < blablubb.length; i++) {
     String s = blablubb[i];
     s = "over";
}

This creates a temporary String with a copy of the value from array and you change only the copy. That's why blablubb[] content stays untouched.

If you want to change values in the array, just use your second option:

for (int i = 0; i < blablubb.length; i++) {         
    blablubb[i] = "over";
}

And, by the way, you can print an array with just one line:

System.out.println(Arrays.toString(blablubb));
like image 149
Adam Stelmaszczyk Avatar answered Oct 25 '22 05:10

Adam Stelmaszczyk


Your for(String s : blablubb) loop is equivalent to the following code:

for(int i = 0; i < blablubb.length; i++ ) {
    String s = blablubb[i];
    s = "over";
}

Hopefully, from this you can see that all you are doing is reassigning a different value to s without changing blablubb[i]. This explains the output you see.

like image 21
cyon Avatar answered Oct 25 '22 06:10

cyon


The for-each loop don't modify the objects contained in the Collection of objects it's iterating over. It's passing the value not the reference.

like image 2
Maxime Piraux Avatar answered Oct 25 '22 07:10

Maxime Piraux