Answer the question
In order to leave comments, you need to log in
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;
}
}
John 25
John 25
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;
10
12
Answer the question
In order to leave comments, you need to log in
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? ))
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question