Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Would a null string passed to any of the system.out.printxxx functions cause crash/exception  RSS feed

 
Angus Comber
Ranch Hand
Posts: 90
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If I run code like this:



I get output str:
as expected. But I thought that passing a null when a String was expected would cause a crash? But it didn't? Was I lucky? why not?


Is it safer to change null strings to "" blank string like this:


 
Kemal Sokolovic
Bartender
Posts: 825
5
Java Python Ruby
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
From API:
public String()
Initializes a newly created String object so that it represents an empty character sequence. Note that use of this constructor is unnecessary since Strings are immutable.

In your code str is initialized to empty string. And there is a difference between empty string and null reference.

Even if you did it like this:

you wouldn't get NullPointerException. But if you try to invoke a method on a null object (of String type, or whatever), you will get it.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!