1. Member
Join Date
May 2014
Posts
43
Rep Power
0

## PointCoordinates

What are the x- and y-coordinates of the Points referred to as p1, p2, and p3 after the following code executes? Give your answer as an x-y pair such as (0, 0). (Recall that Points and other objects use reference semantics.

PHP Code:
```Point p1 = new Point();
p1.x = 17;
p1.y = 9;
Point p2 = new Point();
p2.x = 4;
p2.y = -1;
Point p3 = p2;

p1.translate(3, 1);
p2.x = 50;
p3.translate(-4, 5);```

P1:
P2:
P3:

My guesses were: P1:(20,10) //Correct
P2:(50,-1) //Incorrect
P3:(0,4) //Incorrect

2. ## Re: PointCoordinates

The tricky part is at line 7: p3 points (no pun intended) to the same Point in memory as p2. The change you make to p3 will be performed on the same instance as p2. So, p2 and p3 always return the same values since they point to the same object.

3. Member
Join Date
May 2014
Posts
43
Rep Power
0

## Re: PointCoordinates

But what would the values turn out to be ?

p2.x = 50; that should change the value of p2.x=4 into p2.x=50 i presume, but its still a wrong answer.

4. ## Re: PointCoordinates

Originally Posted by toiletpaper
But what would the values turn out to be ?

p2.x = 50; that should change the value of p2.x=4 into p2.x=50 i presume, but its still a wrong answer.
Yeah, true, but after that, p3 is translated, so the values for p2 change as well, since those variables point to the same object.

5. Moderator
Join Date
Apr 2009
Posts
13,212
Rep Power
23

## Re: PointCoordinates

p1, p2 and p3 are references to Point objects.
They are not the objects themselves.

p1 refers to a Point that was created on this line:
Java Code:
`Point p1 = new Point();`
p2 refers to a Point that was created on this line:
Java Code:
`Point p2 = new Point();`
These are two different objects, so anything done via p1 will not affect the object referred to by p2, and vice versa.

p3 is declared as referring to p2, on this line:
Java Code:
`Point p3 = p2;`
This means that anything done via the p2 reference or the p3 reference will affect the same underlying object. There is only the one object.

#### Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts
•