• 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
  • Ron McLeod
  • Paul Clapham
  • Devaka Cooray
  • Tim Cooke
Sheriffs:
  • Rob Spoor
  • Liutauras Vilda
  • paul wheaton
Saloon Keepers:
  • Tim Holloway
  • Tim Moores
  • Mikalai Zaikin
  • Carey Brown
  • Piet Souris
Bartenders:
  • Stephan van Hulst

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.)
 
I'm gonna teach you a lesson! Start by looking at this tiny ad:
Gift giving made easy with the permaculture playing cards
https://coderanch.com/t/777758/Gift-giving-easy-permaculture-playing
reply
    Bookmark Topic Watch Topic
  • New Topic