0

I was trying out string concatenation and the '+' operator on a string and encountered the following-

String xyz = "Hello" + null;
System.out.println("xyz= " +xyz);
String abc= "Hello".concat(null);
System.out.println("abc= " +abc); 

The output for the first one was : Hellonull
The output for the second one was a Null Pointer exception

I don't understand why there were two different outputs.

Jens
  • 67,715
  • 15
  • 98
  • 113
user2381832
  • 126
  • 1
  • 11

5 Answers5

2

When you concatenate null by + operator, it is always converted to "null" String. This explains the first output Hellonull.

The concat function looks internally like this:

public String concat(String s) {

    int i = s.length();
    if (i == 0) {
        return this;
    } else {
        char ac[] = new char[count + i];
        getChars(0, count, ac, 0);
        s.getChars(0, i, ac, count);
        return new String(0, count + i, ac);
    }
}

Source: String concatenation: concat() vs "+" operator

As you can see, it calls s.length(), which in your case means null.length(); which causes the NullPointerException for your String abc= "Hello".concat(null); statement.

Edit: I just decompiled my own String.concat(String s) function and its implementation looks a little bit different, but the reason for the NullPointerException stays the same.

Community
  • 1
  • 1
Michal Krasny
  • 5,434
  • 7
  • 36
  • 64
2

From Docs

If the reference is null, it is converted to the string "null" (four ASCII characters n, u, l, l).

Otherwise, the conversion is performed as if by an invocation of the toString method of the referenced object with no arguments; but if the result of invoking the toString method is null, then the string "null" is used instead.
pratim_b
  • 1,160
  • 10
  • 29
0

"Hello" + null returns the same result as "Hello".concat(String.valueOf(null)).

String.valueOf(null) returns the string "null".

user253751
  • 57,427
  • 7
  • 48
  • 90
0
/**
 * Concatenates this string and the specified string.
 *
 * @param string
 *            the string to concatenate
 * @return a new string which is the concatenation of this string and the
 *         specified string.
 */
public String concat(String string) {
    if (string.count > 0 && count > 0) {
        char[] buffer = new char[count + string.count];
        System.arraycopy(value, offset, buffer, 0, count);
        System.arraycopy(string.value, string.offset, buffer, count, string.count);
        return new String(0, buffer.length, buffer);
    }
    return count == 0 ? string : this;
}

the source code's first line in contact function calls the null's count. So it will throw Null Pointer exception.

zzy
  • 1,771
  • 1
  • 13
  • 48
0

Calling concat() on a null reference gives NPE, hence different results as "+" operator treats null reference as "null".

Djordje
  • 186
  • 7