• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

toString Doubts

 
JPraveen Kumar
Ranch Hand
Posts: 80
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
Jay Pawar
Ranch Hand
Posts: 411
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

This is what is happening under the hood when you make
System.out.println(obj); // where obj = null
call.


In PrintStream.java file you will see the following code



Now print method in turn calls valueOf method in String.java



here is what valueOf method in String looks like.


Does that give you idea why null is being printed ?


In second case, you are invoking method on a null object which will give you NullPointerException.

Hope this helps you...

[ January 25, 2005: Message edited by: Jay Pawar ]
[ January 25, 2005: Message edited by: Jay Pawar ]
 
Balasubramani Dharmalingam
Ranch Hand
Posts: 116
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
see source code of print(Object o) method in PrintStream class

ie..

public void print(Object obj) {
write(String.valueOf(obj));
}

it calls the static method valueOf(Object o) in the String class
This static method returns String literal "null" if object reference is equal to null .otherwise it calls the toString() method. so the null pointer exception wont occur

see the source code of String.valueOf(Object o ) method

public static String valueOf(Object obj) {
return (obj == null) ? "null" : obj.toString();
}

Balasubramani S D
SCJP 1.4.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic