Reputation: 221
I am new to Java.
I tired the following java code
public class A {
int x;
public static void main(String[] args) {
A a1= new A();
a1.setX(5);
A a2=a1;
System.out.println(a1.getX());
System.out.println(a2.getX());
a2.setX(10);
System.out.println(a1.getX());
System.out.println(a2.getX());
}
public int getX() {
return x;
}
public void setX(int x) {
this.x = x;
}
}
I thought the output will be
5 5
5 10
But when I compile and run the code the output is coming as 5 5
10 10
Why the a1 x value is changing with a2 x?
Upvotes: 1
Views: 67
Reputation: 13
You've declared an object called a1. and set it's value to 5. so its name = a1, value = 5. Let's pretend the address of a1 is 0x123.
Then you've declared an object called a2, and told it it has the same address as a1. when you said a2 = a1. Therefore whatever is in a1 (to start with, 5) will be pointed to by a2 also. And the address of a1 and a2 is, in both cases, 0x123.
Then you set the value in a2 to 10. In other words the value at address 0x123 will be 10. but a1 also has the address 0x123, so it doesn't matter whether you print a1 or a2, they both point to the value 10 that is in the same memory location at 0x123.
It's like the value is in a box which happens to have two different names on it, but it's still the same box with the same address and therefore with the same content.
I hope that helps.
Upvotes: 1
Reputation: 156708
A a2=a1;
This statement causes the a2
variable to represent the same location in memory that a1
represents. Therefore, any changes you make to the object at this memory location are changing the same pieces of memory as if you had been making those changes to a1
.
If you want a2
to point to a different memory location, you'll need to allocate memory to hold the new value, like you did with a1
:
A a2 = new A();
Upvotes: 6
Reputation: 12953
Objects in java are defined by reference. this means that when you do a2 = a1
what it means that a2
points to the same instance as a1
. this means that changing one changes the other as well
Upvotes: 5