Good day. I read about the challenge by value and came across two examples. 1st:

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]); } } 

Here everything seems to be clear. The reference to the string array "y" will coincide with the reference to the array "x" and copying will occur and the answer will be "BB". But here is a second example:

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

Here, for some reason, the answer is "BA", although I thought that the correct answer would be "BB". The line of reasoning was the same as in the first example. Can you please tell me what the trick is in this example? After all, a String is a class, not a type in Java, and in both examples we create an instance of the String class.

  • 3
    Actually, this is not a question of passing parameters ... - m. vokhm

3 answers 3

In the first case, you have an array (we denote it by M , although in Java you can not access it except through a link). The zero element of the array M points first to the string "A" , then to the string "B" . Both x and y , note, refer to the same array M When you change data in an array through any of the links, you change the same data.

In the second case, we have variables x and y , which refer to the same string "A" , and then x starts to refer to another string ( "B" ). It's simple.


Here is an analogy. In the first case, you have a cell. And you and I look at this cell. In the cage, a white rabbit was sitting first, and then a black rabbit was put there. Now you and I look at the cage with the black rabbit.

In the second case, there is no cage, I look at the white rabbit, you look at the same rabbit as I, and then I turned away and began to look at the black rabbit. Well, yes, now we look at different rabbits.

Now replace the rabbits with strings, a cell with an array, “look” to “have a link”.


You should not look for universal, simple rules like “if I change this thing, it will also change.” Or "will not change." Or "will change if the level of indirection is greater than 1." Talk about the meaning of operations every time.


Could not resist, added pictures, which spoke @void.

See it. First example:

 String[] x = {"A"}; 

String [] x = {"A"};

 String[] y = x; 

String [] y = x;

 x[0] = "B"; 

x [0] = "B";

Second example:

 String x = "A"; 

String x = "A";

 String y = x; 

String y = x;

 x = "B"; 

x = "B";

So clearer?

  • I can not understand the difference, because the string String y = x; is present in both examples. Especially String is a reference type. So the link (in both examples) indicates that the data from one array will be copied to another. By "In the first case, you have an array (we denote it M)" do you mean a pool of strings? - Drylozav
  • in the first example you changed the object, and who told you that in the second example you changed the object U ?? You just changed the link U. object that you did not touch. - arg
  • one
    A pool of lines nothing to do with. Do you know what String[] means? This is not a String . Read a better analogy about rabbits. And once again, do not think that once and there and there it says “ y = x ”, then you will behave the same way. Think of the meaning. - VladD
  • one
    These are different types. In the first case, you do not change the whole cage, but only a rabbit in a cage. Look carefully at the assignment x[0] = "B" . - VladD
  • one
    @Vlad - great, plus! @Drylozav - do not consider it ironic, do not think that Java behaves incorrectly . To put it more precisely, I think that you know, I am more than sure, that Java does not behave in a way that is wrong , so I just want to say that you are on the right track. Get a piece of paper and draw what @VladD told you about. Schematically imagine. Draw lines A and B with rectangles. Draw an array whose element points to line A. {.pause.} And then graphically analyze. Comment does not allow to write more. PS Plus for the question - I read it myself - void

In the first case, you have 2 references to the same array.

 String[] x = {"A"}; //x указывает на массив {"A"} (x[0] == "A") String[] y = x; //x и y указывают на массив {"A"} (x == y; x[0] == y[0]; x[0] == "A"; y[0] == "A") x[0] = "B"; //в массиве {"A"} строка с индекcом 0 поменялась на строку "B", изменилось состояние массива и теперь это массив {"B"}. Но это все еще тот же самый объект (x == y; x[0] == y[0]; x[0] == "B"; y[0] == "B") 

In the second case, you have two different references to instances of the String class:

 String x = "A"; //x указывает на строку "A" String y = x; //x и y указывают на строку "A" (x == y) String x = "B" //x указывает на строку "B", y указывает на строку "A" (x != y) 
  • But what's the difference? because in the first example, there are also two references to an instance of the String class, which are represented by a string array, and as you said, there are 2 references that point to the same array. In this example, the same thing: two links. - Drylozav
  • in the first example there is NO reference to the String instance. I do not see it at all. there is a link to MASSIF which is typed by String. - arg
  • how not? because String is a class, any instance of which spawns an object - Drylozav
  • try replacing String x = "A" with String x = new String ("A") - Sevak Avetisyan
  • @Dryzolav I added the answer. I hope it became clearer. - a_gura pm

It is impossible to change the contents of the created line, at least in the safe (safe) code and without reflection. Therefore, when changing lines, you do not change the lines themselves, but the values ​​of the variables pointing to the lines. For example, the code s = s.Replace ("foo", "bar"); does not change the contents of the string s, which was before the call to the Replace method — it simply reassigns the variable s to the newly-formed string, which is a copy of the old one except for all the substrings “foo” replaced by “bar”.

  • one
    Not relevant to the issue. The situation with the variable object would be the same in the case of assignment. - Qwertiy