3

When I watched code examples in Java, I saw a strange code:

public class Application {
     public static void main(String[] args) {
          String[] x = {"A"};
          String[] y = x;
          x[0] = "B";
          System.out.print(x[0] + " " + y[0]);
     }
}

And I don't understand, why the result "B B" is correct? When I created and initialized an arrays x and y and assigned zero element of array x is equal to B, I think that an answer must be "B A".

Cœur
  • 37,241
  • 25
  • 195
  • 267
Drylozav
  • 183
  • 1
  • 9

4 Answers4

6
String[] y = x;

means that the array y now refers to the array x.

Consequently changing the contents of x means the contents of y change (since they're the same).

To elaborate, in Java, this:

String[] y = {...};

means that you're declaring y to be a reference to an array, not the array itself. So when you assign, you're assigning a reference and not copying the object values.

Brian Agnew
  • 268,207
  • 37
  • 334
  • 440
  • tell me please where I can read it in more detail ? – Drylozav Oct 29 '13 at 14:28
  • But, why this code : public class Application { public static void main(String[] args) { String x = "A"; String y = x; x = "B"; System.out.print(x + " " + y); } } shows the correct result "B A" – Drylozav Oct 30 '13 at 16:00
2

That's now how we copy arrays in Java. That's what you are doing now:

  x        y
+---+    +---+ 
| a |<---|-- |
+---+    +---+

So when you change the content of x, the content of y will be changed.

If you want to copy the array, you can use Arrays#copyOf:

String[] y = Arrays.copyOf(x, x.length);

Now, if you chagne x, y won't be changed.

Maroun
  • 94,125
  • 30
  • 188
  • 241
1

In Java Array are considered as object reference. You are changing the value to the reference.

For illustrate try this one

   String[] x = {"A"};
   String[] y = x;    
   System.out.println(x==y);   //true -> X and Y are pointing the same reference. 
Prabhakaran Ramaswamy
  • 25,706
  • 10
  • 57
  • 64
0

Java always does copy by value when an assignment operator is called. You declared yor first array like this:

String[] x = {"A"};

and x now holds reference to this array. When you assign x to y, it just copies reference to array x to y variable, so now both x and y represent the same array. When you change something in one array, the change affect other array too. Look here for better understanding

vanomart
  • 1,739
  • 1
  • 18
  • 39