Search code examples
javanullstring-concatenation

What happens when string is concatenated with null?


What's the work of null operator in string, on concatenation the output is null+string why? the prg is.

public static void main2()
{
    String s1=null;
    String s2="";
    System.out.println(s1);
    System.out.println(s2);
    s1=s1+"jay";
    s2=s2+"jay";
    System.out.println(s1);
    System.out.println(s2);
}

what's happening here?


Solution

  • null is not an operator. null is a literal that represents a null reference, one that does not refer to any object. null is the default value of reference-type variables. It's mean that the string variable or your another object type variable is not pointing to anywhere in the memory.

    And when you concatenate it with another string. It will added to that string. why? because If the reference is null, it is converted to the string "null".

    String s1=null;
    String s2="";
    System.out.println(s1);
    System.out.println(s2);
    s1=s1+"jay";
    s2=s2+"jay";
    
    // compiler convert these lines like this,
    // s1 = (new StringBuilder()).append((String)null).append("jay").toString();
    // s2 = (new StringBuilder()).append((String)"").append("jay").toString();
    
    System.out.println(s1);
    System.out.println(s2);
    

    It will print nulljay