Help coderanch get a
new server
by contributing to the fundraiser
  • 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
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

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: 4844
52
  • 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.
 
Ew. You guys are ugly with a capital UG. Here, maybe this tiny ad can help:
We need your help - Coderanch server fundraiser
https://coderanch.com/t/782867/Coderanch-server-fundraiser
reply
    Bookmark Topic Watch Topic
  • New Topic