Back to questions
JuniorTheoryCommon
What happens when this program is compiled and run?
public class Main {
public static void main(String[] args) {
Point p = new Point();
Point q = p;
p = null;
System.out.println(q.x);
System.out.println(p.x);
}
}
class Point { int x; }Prints 0, then a NullPointerException is thrown
- Expecting the exception at once:
p = nullerases the reference inponly, andqstill leads to the point, so0prints first. - Expecting
0twice or a compile error: a field read throughnullthrowsNullPointerExceptionat run time, and javac does not check it.
- How would you change the last line so that it prints nothing instead of throwing when
pisnull? - What does
System.out.println(p)print whenpisnull?