2014-11-14 2 views
0

내가 문자열에 문자열 연결하고 '+'연산자를 시도하고 첫 번째에 대한 다음과 같은 -문자열 연결과 + 연산자

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

출력을 발생되었다이었다 Hellonull
출력 두 번째는 Null 포인터 예외

두 개의 다른 출력이있는 이유를 이해할 수 없습니다.

답변

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을 의미한다(); 어떤 String abc= "Hello".concat(null); 문에 대한 NullPointerException이 발생합니다.

편집 : 난 그냥 내 자신의 String.concat (문자열들) 기능을 디 컴파일하고 실행 조금 다른 보이지만, 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 포인터 예외가 발생합니다.

2

null 참조에 CONCAT()를 호출 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

에서 NPE는 "+"연산자 "NULL"와 같은 널 레퍼런스를 처리로서, 따라서 상이한 결과를 제공한다.