D
D
Dmitry072016-08-16 15:32:12
Java
Dmitry07, 2016-08-16 15:32:12

Why doesn't changing a copy of an int always change the original int?

Good day.
There are two examples where we work with a copy of an int variable. In the first example, changing a 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;
    }
}

Final result:
John 25
John 25

i.e. 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(y);
  }
//В примере параметром метода является int x, что немного путает с толку. Может быть любой буквой.
  int change(int x){
    x = 12;
    return x;

we get the final result:
10
12

i.e. x still points to '10'. What could be the reason for such a difference?
Thanks to.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
T
Therapyx, 2016-08-16
@Dmitry07

Option 1: Look, you created an object on 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 further, whatever you do with it, it will remain 10 in the main. You changed it to 12 in the change function and 12 is only there, nowhere else, after which you simply return the value 12, which initializes the y variable.
Understandably? Or something better to tell? ))

A
Alexey, 2016-08-16
@alsopub

Simple types are passed by value, complex types are passed by reference.
Or am I missing something in the code.
In the first case, you passed not an object, but a reference to the object, and it was changed through the reference.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question