Back to questions
JuniorTheoryCommon
What does the program print?
public class Main {
public static void main(String[] args) {
Point p = new Point();
p.x = 1;
Point q = p;
q.x = 7;
q = new Point();
q.x = 9;
System.out.println(p.x);
}
}
class Point { int x; }7
- Expecting
1:Point q = pcopies only the reference, sopandqlead to one object andq.x = 7is seen throughp. - Expecting
9:q = new Point()makes onlyqlead to a new object;pkeeps the old one, wherexis still 7.
- How would you make
qan independent copy of the pointp? - What would
p == qprint right afterPoint q = p?