• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

null Strings concatenation

 
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
 
Ranch Hand
Posts: 7729
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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 ]
 
ranger
Posts: 17347
11
Mac IntelliJ IDE Spring
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thank you a lot.
 
reply
    Bookmark Topic Watch Topic
  • New Topic