2014-11-14 3 views
0

Я пытался из конкатенации и оператор «+» на строку и встречается включено следующее:Объединение строк и оператор +

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

Выход для первого был: Hellonull
Выход для второго было Исключение нулевого указателя

Я не понимаю, почему были два разных выхода.

ответ

2

Когда вы связываете null оператором +, он всегда преобразуется в строку «null». Это объясняет первый выход Hellonull.

Функция CONCAT выглядит внутренне так:

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); 
    } 
} 

Источник: String concatenation: concat() vs "+" operator

Как вы видите, он вызывает s.length(), который в вашем случае означает null.length(); который вызывает исключение NullPointerException для вашего оператора String abc= "Hello".concat(null);.

Edit: Я просто декомпилированы свою собственную функцию String.Concat (String s) и его реализация выглядит немного по-другому, но причина NullPointerException остается тем же самым.

0

"Hello" + null возвращает тот же результат, что и "Hello".concat(String.valueOf(null)).

String.valueOf(null) возвращает строку «null».

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; 
} 

Первая строка исходного кода в контактной функции вызывает кол-во нулей. Таким образом, он будет генерировать исключение Null Pointer.

2

От 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. 
0

Calling CONCAT() на нулевой ссылки дает NPE, следовательно, различные результаты, как "+" оператор обрабатывает пустую ссылку как "нуль".

Смежные вопросы