System.out.println on a Null Object
Posted: Fri Jan 31, 2014 8:33 pm
I do not understand on the Java 7 Exam question (Practice Tests -> Tough Test -> Question 7)
I tried the following example
which is pretty similar to the example that is given. In the above example, there is a small change as mentioned in the Different line comment above. This returns Null Pointer exception at run time while the System.out.println(o); does not return an error.
Could you please explain of what is going wrong and why is t throwing an NPE?
I tried the following example
Code: Select all
class ToString
{
int i;
public String toString()
{
if (i == 0)
{
return null;
}
else
{
return "2";
}
}
ToString(int i){this.i = i;}
public static void main(String[] args)
{
ToString t = new ToString(0);
ToString t1= new ToString(1);
//
System.out.print(""+t1);
System.out.print(t); //Different line
Object o = null;
System.out.println(o);
}
}
Could you please explain of what is going wrong and why is t throwing an NPE?