Meaningless Drivel is fun!
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes toString Doubts Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "toString Doubts" Watch "toString Doubts" New topic

toString Doubts

JPraveen Kumar
Ranch Hand

Joined: Aug 31, 2004
Posts: 80
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.

Jay Pawar
Ranch Hand

Joined: Aug 27, 2004
Posts: 411

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

In file you will see the following code

Now print method in turn calls valueOf method in

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 ]

Cheers,<br />Jay<br /> <br />(SCJP 1.4)<br />Heights of great men were not achieved in one day, they were toiling day and night while their companions slept.
Balasubramani Dharmalingam
Ranch Hand

Joined: Dec 06, 2004
Posts: 116
see source code of print(Object o) method in PrintStream class


public void print(Object 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.
I agree. Here's the link:
subject: toString Doubts
jQuery in Action, 3rd edition