15

Here is my class, where i am concatenating two string. String concatenate with null using + operator execute smoothly but throws NullPointerException with concate() method.

public class Test {

    public static void main(String[] args) {

        String str="abc";
        String strNull=null;

        System.out.println(strNull+str);

        str.concat(strNull);
    }
}

can anybody tell me the reason behind it ??

9 Answers 9

16

Case 1:

 System.out.println(strNull+str);  // will not give you exception

From the docs(String conversion)

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.

Case 2:

str.concat(strNull);  //NullPointer exception

If you see the source of concat(String str) it uses str.length(); so it would be like null.length() giving you a NullPointerException.

Sign up to request clarification or add additional context in comments.

4 Comments

so why doesn't System.out.println(strNull+str) give an output of "nullabc"?
@Blip If the reference is null, it is converted to the string "null" will not throw nullpointer because toString() is not called on it
Ok so null + str is converted to "null"+"abc" according to the example above. so the output should be "nullabc"?
it will give nullabc as output. i checked it before. but i want to know why different Strategies of + and concate()
8

If you see in java.lang.String source, and use null as parameter. NPE is thrown in first line in length() method.

public String concat(String str) {
    int otherLen = str.length();//This is where NullPointerException is thrown
    if (otherLen == 0) {
        return this;
    }
    getChars(0, count, buf, 0);
    str.getChars(0, otherLen, buf, count);
    return new String(0, count + otherLen, buf);
}

3 Comments

this is a good info but why designer write in this way ?? what is the reason
This is only a reason why the NPE is thrown, but not why it was implemented this way. E.g. the equals method does check for null before doing anything.
but why doesn't null + str throw a NullPointerException?
4

@Blip : 1) null + "ABC"

Straight forward answer to your question is + operator in java uses StringBuilder.append method to concat the strings.

And StringBuilder.append() method treats null object as "null" String. Hence null + "ABC" won't give Null Pointer exception but rather prints nullABC.

2) String.concat()

And yes, there is no null check before string.length() method in concat() function of String class. Hence it is throwing null pointer exception.

Hope this answers your question.

Comments

2

Because inside concat method in String class, length method is getting invoked on passed parameter , due to which NPE is thrown.

public String concat(String str) {
        int otherLen = str.length();<------
        if (otherLen == 0) {
            return this;
        }
        int len = value.length;
        char buf[] = Arrays.copyOf(value, len + otherLen);
        str.getChars(buf, len);
        return new String(buf, true);
    }

6 Comments

but why doesn't null + str throw a NullPointerException?
Because If the reference is null, it is converted to the string "null"
because + toString() and concatenate the values.
You can also refer to section 5.1.11. of JLS that states If the reference is null, it is converted to the string "null" (four ASCII characters n, u, l, l).
@Blip it does gives an output of nullabc for the given code String strNull = null; System.out.println(strNull + "abc");
|
2

Actual implementation of concate method is like this . this method need an object of type String as a parameter and if argument is null then it throws Null Pointer Exp.

public String concat(String paramString)
  {
    int i = paramString.length();
    if (i == 0) {
      return this;
    }
    int j = this.value.length;
    char[] arrayOfChar = Arrays.copyOf(this.value, j + i);
    paramString.getChars(arrayOfChar, j);
    return new String(arrayOfChar, true);
  }

2 Comments

but why doesn't null + str throw a NullPointerException?
because it convert null into "null" (ASCI characters 'n','u','l','l') while conversion. it is mentioned in java doc at oracle website
2

String.concat() need an object of type String as a parameter.

There is no type which null is an instanceof. Refer JLS:

15.20.2 Type Comparison Operator instanceof

RelationalExpression: RelationalExpression instanceof ReferenceType At run time, the result of the instanceof operator is true if the value of the RelationalExpression is not null and the reference could be cast to the ReferenceType without raising a ClassCastException. Otherwise the result is false.

1 Comment

useful info but why doesn't null + str throw a NPE
2

concate() method creates new String() object under the hood.

where as + combines\ concatenates values by using toString() method. That's why when we use + it continents "somevalue".append(null).toString().

for reference see this question.

1 Comment

@Muneed your answer is logical among all this, can you refer me some documentation about your explanation.
1

The String class holds an array (probably an ArrayList) of characters. When you call .concat() it goes through and adds every character from the second string to the first.

If the first String is null, there is nothing to add to, causing a NullPointer Exception. Try initializing Strings with "".

1 Comment

i think String use CharSequence. by the way i dont need a solution , i know it, i just want the reason behind it
-3

Initializing a null String with "" should work.

1 Comment

i dont need a solution , i know it, i just want the reason behind it

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.