• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Tim Cooke
  • Campbell Ritchie
  • Paul Clapham
  • Ron McLeod
  • Liutauras Vilda
Sheriffs:
  • Jeanne Boyarsky
  • Rob Spoor
  • Bear Bibeault
Saloon Keepers:
  • Jesse Silverman
  • Tim Moores
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
Bartenders:
  • Piet Souris
  • Al Hobbs
  • salvin francis

String.valueOf() method

 
Ranch Hand
Posts: 42
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I am using an OLD compiler and when I do the following:
System.out.println(String.valueOf(null));
//this gives me NullPointerException at runtime
but if I do this: Object o=null;
System.out.println(String.valueOf(o));
//this gives me "null" in the output.
and the API says if the argument is null ,it should return "null". what is the deal here?
please help!!! much appreciated.
chun
 
"The Hood"
Posts: 8521
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Define OLD - what version are you using?? And WHY?
 
Bartender
Posts: 783
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Chun,
JDK1.3 will also give you a NullPointerException with that code. The reason why is String.valueOf(null) invokes the best matching overloaded version of valueOf() which is String.valueOf(char[]). This method is implemented with the following code:

Notice that it's creating a new String object for a char[]. If you modify your code to set a char[] data = null; and call String.valueOf(data);, the JRE will throw a NullPointerException.
For Object o = null;, the code is calling the overloaded version of String.valueOf(Object o) which looks like:

Notice the check for a null object.
-Peter
 
Ranch Hand
Posts: 130
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thats a beauty. Great explanation Peter.
Thanks a lot.
Natarajan

------------------

***********************************************
Sun Certified Programmer for Java 2 Platform
***********************************************
 
reply
    Bookmark Topic Watch Topic
  • New Topic