GeeCON Prague 2014*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes null Strings concatenation 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 "null Strings concatenation " Watch "null Strings concatenation " New topic
Author

null Strings concatenation

Al Morrissey
Greenhorn

Joined: Jul 19, 2005
Posts: 3
public class StringTest {

static String str1;
static String str2;

public static void main( String [] arg){
str2 = str1 + str2 ;
System.out.println ( "str2 : " + str2);
System.out.println ( "str2 == null " + (str2 == null ));}
}

As the strings str1 and str2 were not initialized, they are null. Why after
str2 = str1 + str2
I was expected str2 to still be null but the output is:
str2 : nullnull
str2 == null false
and I do not understand why. str1 and str2 are both null not having value "null", so I do not understand from where there is that nullnull value.

Thanks
Barry Gaunt
Ranch Hand

Joined: Aug 03, 2002
Posts: 7729
Check out JLS V3.0 Section 15.18.1 (String concatenation operator +):
If an operand of type String is null, then the string "null" is used instead of that operand


Both your opeands are null, so what you get is "null" + "null", or "nullnull".
[ July 24, 2005: Message edited by: Barry Gaunt ]

Ask a Meaningful Question and HowToAskQuestionsOnJavaRanch
Getting someone to think and try something out is much more useful than just telling them the answer.
Mark Spritzler
ranger
Sheriff

Joined: Feb 05, 2001
Posts: 17250
    
    6

Originally posted by Barry Gaunt:
Check out JLS V3.0 Section 15.18.1 (String concatenation operator +):


Both your opeands are null, so what you get is "null" + "null", or "nullnull".

[ July 24, 2005: Message edited by: Barry Gaunt ]


And therefore str2 is no longer null, but "nullnull" hence (str2 == null) produces false.

Mark


Perfect World Programming, LLC - Two Laptop Bag - Tube Organizer
How to Ask Questions the Smart Way FAQ
Al Morrissey
Greenhorn

Joined: Jul 19, 2005
Posts: 3
Thank you a lot.
 
GeeCON Prague 2014
 
subject: null Strings concatenation