Hi All,
As per my understanding toString is called whenever the object is directly referred to in a println command. We can override it to provide a custom descriptive message of the object based on its fields.
toString is declared as public
String toString(). Since the function is non-static, I should get a runtime Null Pointer error when it is invoked either directly (as a function invoke) or via an indirect call (through the object) when the calling object points to null. Please explain that why null is printed in the first println stattement of the code.
class cls {
public static void main (String a[]) {
cls ob=null;
try {System.out.println (ob);}
catch (Exception e) {System.out.println ("ERR in obj");} //Displays null
try {System.out.println (ob.toString());}
catch (Exception e) {System.out.println ("ERR in tos");} //Displays catch error.
}
}
Tx JPK