• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

why does System.out.println(s) print out null when s is null String reference?

 
Judy YU
Ranch Hand
Posts: 30
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The following code printed out "nullnull" instead of throwing NullpointerException at run time. Why?
public class AStringQuestion
{
static String s1;
static String s2;
public static void main(String args[])
{
s2 = s1+s2; // I would assume the exception will be thrown here.
System.out.println(s2);
}
}
Thanks.
Judy
 
Sean Casey
Ranch Hand
Posts: 625
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Since your two String objects are member variables they are initialized to null, and null respectively. If they were local variables and they weren't initialized, you'd get a compiler error citing that they may not have been initialized yet. Keep in mind that in this instance both String objects have to be static since you are accessing them through a static method(main).
[This message has been edited by Sean Casey (edited February 01, 2001).]
 
Peter Tran
Bartender
Posts: 783
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Judy,
Somewhere in the VM, the overloaded "+" (which btw only is only valid for String objects) will invoke the String.valueOf() method.

Notice the check for null. If the input parameter is null, then it will return a "null" string. This is why you get "nullnull" as your output when you print s2.
-Peter
 
Balu Ramachandran
Greenhorn
Posts: 16
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
HI,
ur refering static String variable with static method(main())
default value for String class is "null"
hear, s2=s1+s2 ===> s2=null+null (makes String concatination)
and gives as output =======> nullnull


------------------
R.Balu
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic