Win a copy of The Java Performance Companion this week in the Performance forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

null Strings concatenation

 
Al Morrissey
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 7729
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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 ]
 
Mark Spritzler
ranger
Sheriff
Posts: 17278
6
IntelliJ IDE Mac Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
Al Morrissey
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you a lot.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic