Good day.

There are two examples in which we work with a copy of an int variable. In the first example, changing the copy of an int changes the original int:

class Person{ String name; int age; Person(String s, int i){ name = s; age = i; } } class Test{ public static void main(String args[]){ Person p1 = new Person("John", 22); Person p2 = new Test().change(p1); System.out.println(p1.name + " " + p1.age); System.out.println(p2.name + " " + p2.age); } private Person change(Person p){ Person p2 = p; p2.age = 25; return p2; } } 

The final result:

 John 25 John 25 

that is, now p1.age also points to '25'. However, in the second case:

 class Test{ public static void main(String args[]){ int x = 10; int y = new Test().change(x); System.out.println(x); System.out.println(у); } //В примере параметром является int x, что немного путает с толку. Может быть любой буквой. int change(int x){ x = 12; return x; } } 

we get the final result:

 10 12 

that is, x still indicates '10'. What could be the reason for this difference?

Thank you.

  • In the first case, no copy is made. In the second case, the variable of type int is copied twice. - Pavel Mayorov
  • But how is Person p2 created then? Is this not a modified copy of Person p1? - Dmitry08
  • Not. This is the second link to the same object. Check: System.out.println(p1 == p2); - Pavel Mayorov
  • Strange, when you try to add a code, it gives syntax error on tokens. - Dmitry08
  • So, add to the wrong place. - Pavel Mayorov

1 answer 1

With your permission, I will add a comment from the toaster:

Option 1: Look, you created an object in the heap with the address "let it be 111", after which you assign this address to the 2nd object. It turns out that object 2 has the same address "111", then you change the age to 25 in this address "111", respectively, both objects become with address 111.

Option 2: x = 10 is a local variable, if you pass it on, then so that you do not do it - it will remain in Maine 10. You changed it to 12 in the function change and 12 it only there, nowhere else, after which you simply return the value 12, which initializes the variable y.