aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes why does System.out.println(s) print out null when s is null String reference? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "why does System.out.println(s) print out null when s is null String reference?" Watch "why does System.out.println(s) print out null when s is null String reference?" New topic
Author

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

Judy YU
Ranch Hand

Joined: Nov 19, 2000
Posts: 30
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

Joined: Dec 16, 2000
Posts: 625
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

Joined: Jan 02, 2001
Posts: 783
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

Joined: Oct 16, 2000
Posts: 16
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


R.Balu
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: why does System.out.println(s) print out null when s is null String reference?
 
Similar Threads
polymorphism question
another Question.
Inheritence
it's long but i can't help it.
Strings