• 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
  • Tim Cooke
  • Ron McLeod
  • paul wheaton
  • Jeanne Boyarsky
Sheriffs:
  • Paul Clapham
  • Devaka Cooray
Saloon Keepers:
  • Tim Holloway
  • Roland Mueller
  • Himai Minh
Bartenders:

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: 4907
60
  • 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.
 
reply
    Bookmark Topic Watch Topic
  • New Topic