• 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:
  • Campbell Ritchie
  • Paul Clapham
  • Ron McLeod
  • Jeanne Boyarsky
  • Tim Cooke
Sheriffs:
  • Liutauras Vilda
  • paul wheaton
  • Henry Wong
Saloon Keepers:
  • Tim Moores
  • Tim Holloway
  • Stephan van Hulst
  • Carey Brown
  • Frits Walraven
Bartenders:
  • Piet Souris
  • Himai Minh

NullPointerException with String

 
Ranch Hand
Posts: 173
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi Folks,

I have this doubt.



In the above code, x.toString gives a NullPointerException. I believe this is due to the reference variable x not pointing anywhere as it's declared null.
That being the case, why is the line System.out.print(x) printing null to the console? Hope someone can explain why this difference. Thanks.

 
Enthuware Software Support
Posts: 4599
45
  • Likes 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

John Paterson wrote:Hi Folks,

I have this doubt.



In the above code, x.toString gives a NullPointerException. I believe this is due to the reference variable x not pointing anywhere as it's declared null.
That being the case, why is the line System.out.print(x) printing null to the console? Hope someone can explain why this difference. Thanks.


Accessing a null reference always causes the JVM to throw NPE.
The print method simply checks the input for null before invoking toString on it. If the input is null, it prints "null". That is why there is no NPE.
 
Greenhorn
Posts: 16
1
  • Likes 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi,

Following is the Java implementation ref.. http://www.docjar.com/html/api/java/io/PrintStream.java.html

public void print(String s) {
666 if (s == null) {
667 s = "null";
668 }
669 write(s);

So if s is null, "null" string is printed. I hope it helps.

Thanks
Amit
 
John Paterson
Ranch Hand
Posts: 173
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi guys,

Thanks for reply. Appreciate it.
 
This tiny ad is suggesting that maybe she should go play in traffic.
Free, earth friendly heat - from the CodeRanch trailboss
https://www.kickstarter.com/projects/paulwheaton/free-heat
reply
    Bookmark Topic Watch Topic
  • New Topic