• 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
  • paul wheaton
  • Devaka Cooray
Sheriffs:
  • Jeanne Boyarsky
  • Tim Cooke
  • Liutauras Vilda
Saloon Keepers:
  • Tim Moores
  • Tim Holloway
  • Stephan van Hulst
  • Carey Brown
  • Piet Souris
Bartenders:
  • salvin francis
  • Mikalai Zaikin
  • Himai Minh

No NullPointerException?

 
Ranch Hand
Posts: 39
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Why this code doesn't throw an exception?
 
John Johnson
Ranch Hand
Posts: 39
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Um, okay, I think I got it. Please correct me if I'm wrong. No exceptions are thrown because nothing really happens to the object that was passed to append(). It just got casted to a string. If we were to call some methods like length(), then we would've gotten an exception. So NullPointerException is thrown only if we try to use members of the class.
 
Wanderer
Posts: 18671
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Have you looked at the documentation for the append() method? It says exactly what should happen here. Not all methods throw NullPointerException if you pass them a null.

Note that this is more detail than you need for SCJP. The exact behavior of a specific method like append() isn't that important. Now if s1 had been null, then that would throw a NullPointerException, and that's a general enough rule that are expected to know something like that for SCJP.
 
Sheriff
Posts: 11343
Mac Safari Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Certainly if you try to dereference a null reference, you will get an exception.

But in situations like this, it's often informative to check the API. For StringBuffer's append(Object) method, it states, "The argument is converted to a string as if by the method String.valueOf..." So the question becomes: How does String.valueOf handle a null value? And writing a bit of code around what you have will answer this.

(Note that nothing is "cast" to type String here.)
 
Police line, do not cross. Well, this tiny ad can go through:
ScroogeXHTML - a fast and small RTF to HTML5 and XHTML converter library
https://coderanch.com/t/742149/ScroogeXHTML-RTF-HTML-XHTML-converter
reply
    Bookmark Topic Watch Topic
  • New Topic