1

The following code makes me mad:

private String blahBlah(){
    return null;
}

@Test
public void myTest(){
    System.out.println(blahBlah()); //Good, output "null"
    Object obj = blahBlah();
    System.out.println(obj.toString()) //Good as above
    //System.out.println(blahBlah().toString()); //Bad, NullPointerException
    //System.out.println(((Object)blahBlah()).toString()); //Bad as above
}

Can anyone explain the above behavior?

UPDATE:

The above code is NOT the truth. What I actually experienced is that I received NullPointerException and I track back to the call of toString(), and I tried different workarounds including in-statement casting but it does'nt work. But after I use seperated cast I accidentally removed the toString() call so it WORKED.

2
  • 3
    Erm... You sure the third line of myTest doesn't throw an exception? Commented Feb 10, 2012 at 2:13
  • Sorry, I have changed from the observed code. I will fix it. Commented Feb 10, 2012 at 2:21

3 Answers 3

1

Easy.

You can print a null; you just can't de-reference a null value.

Sign up to request clarification or add additional context in comments.

2 Comments

This explain is enough for the direct call of toString(). However, how would you explain the difference of the in-statement cast and the separated cast?
@EarthEngine, duffymo is correct. The simplest explanation to your code example above is that blahBlah() is not consistently returning null or you are not running the code in that sample. Have you ruled both of those out in a debugger?
0

Because you are returning a string pointing at null instead of pointing at a string with the value null. Try changing return null to return "".

Comments

0

You can use String.valueOf(Object) to get the toString output from an object, or null if the value passed in is null.

http://docs.oracle.com/javase/7/docs/api/java/lang/String.html#valueOf(java.lang.Object)

public static String valueOf(Object obj)

Returns the string representation of the Object argument.

Parameters:
obj - an Object.

Returns:
if the argument is null, then a string equal to "null"; otherwise, the value of obj.toString() is returned.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.