Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

two of the same program produces different results

Tags:

java

Yesterday I asked the a question about reference by value, strange сopy values ​​from one array to another, and thought that I understood the answer after seeing this code:

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

Then I saw this example which is identical to the first:

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

And I do not understand why, in this example, the correct answer will be B A, instead of B B. I think, that I declare x, and then y refers to x.

like image 246
Drylozav Avatar asked Nov 25 '25 03:11

Drylozav


1 Answers

First example:

You have declared a String array whose only member is "A". You declare another String array and assign it x. Now you have two array references referring to the same array. You change the contents to be "B", so it's visible to both array references. You modified the contents of the only array object present.

Second example:

You have declared a String whose contents is "A". You declare another String and assign it x. Now you have two string references referring to the same String. You change the variable x to be "B", and now x and y are referring to different strings, so you see "B A". You didn't change the original string object (Strings are immutable).

like image 128
rgettman Avatar answered Nov 26 '25 17:11

rgettman