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);
}
}
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?
Nothing is going wrong. It is just a peculiarity of the implementation of the print() method of PrintStream class (which is the type of out object). If it gets null as an argument, it prints null instead of throwing a NPE but if it gets a non-null object, it calls methods of other classes to generate a String and one of those other methods is throwing an NPE.
Exception in thread "main" java.lang.NullPointerException
at java.io.Writer.write(Unknown Source) <---------------Implementation of this method throws NPE.
at java.io.PrintStream.write(Unknown Source)
at java.io.PrintStream.print(Unknown Source)
at ToString.main(TestClass.java:27)
at TestClass.main(TestClass.java:39)
So basically, that is just how the classes involved in printing are implemented. Nothing special.
HTH,
Paul.
If you like our products and services, please help us by posting your review here.
Check out the javadoc for print method of PrintStream. It explicitly states that if you pass null, it prints "null".
In case of ""+t, this returns a string containing "null" because that is how + operator is overloaded for Strings. If one operand is null, it appends "null" to the other operand.
If you like our products and services, please help us by posting your review here.