1

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?

OneCricketeer
  • 179,855
  • 19
  • 132
  • 245
JVJplus
  • 97
  • 1
  • 3
  • 11

2 Answers2

2

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

Pirate
  • 2,886
  • 4
  • 24
  • 42
2

null is an "implicit" value assigned to a reference to indicate the absence of an object. It is not an operator.

When you perform concatenation of a string and another type, the other value is simply converted to its "String" representation using String.valueOf(object) and appended to the first String.

For example:

"XYZ" + 1

=> "XYZ" + String.valueOf(1)

=> "XYZ" + "1"

=> "XYZ1"

Similarly,

"Jay" + null

=> "Jay" + String.valueOf(null)

=> "Jay" + "null"

=> "Jaynull"


See implementation of String::valueOf(Object) method here. It is clearly evident that if the object is null, a string "null" should be returned.

Pro Tip: Try putting a break point on the return statement, you will see this code executing while running a java program with string + object concatenation.

/**
 * Returns the string representation of the {@code Object} argument.
 *
 * @param   obj   an {@code Object}.
 * @return  if the argument is {@code null}, then a string equal to
 *          {@code "null"}; otherwise, the value of
 *          {@code obj.toString()} is returned.
 * @see     java.lang.Object#toString()
 */
public static String valueOf(Object obj) {
    return (obj == null) ? "null" : obj.toString();
}

Hope this helps!

anacron
  • 6,443
  • 2
  • 26
  • 31