Win a copy of JDBC Workbook this week in the JDBC and Relational Databases forum
or A Day in Code in the A Day in Code forum!
  • 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 all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Paul Clapham
  • Jeanne Boyarsky
  • Junilu Lacar
  • Henry Wong
Sheriffs:
  • Ron McLeod
  • Devaka Cooray
  • Tim Cooke
Saloon Keepers:
  • Tim Moores
  • Stephan van Hulst
  • Frits Walraven
  • Tim Holloway
  • Carey Brown
Bartenders:
  • Piet Souris
  • salvin francis
  • fred rosenberger

No NullPointerException?

 
Ranch Hand
Posts: 39
  • Mark post as helpful
  • send pies
  • 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
  • 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
  • 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
  • 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.)
 
Happily living in the valley of the dried frogs with a few tiny ads.
Devious Experiments for a Truly Passive Greenhouse!
https://www.kickstarter.com/projects/paulwheaton/greenhouse-1
    Bookmark Topic Watch Topic
  • New Topic