Programing

문자열과 문자의 연결

lottogame 2020. 12. 25. 08:58
반응형

문자열과 문자의 연결


다음 진술,

String string = "string";   

string = string +((char)65) + 5;
System.out.println(string);

출력을 생성 stringA5합니다.


그러나 다음은

String string = "string";

string += ((char)65) + 5;
System.out.println(string);

생산 string70.

차이점은 무엇입니까?


이 동작은 연산자 우선 순위와 문자열 변환의 조합의 결과로 나타납니다.

JLS 15.18.1 은 다음 같이 설명합니다.

하나의 피연산자 식만 String 유형이면 다른 피연산자에서 문자열 변환 (§5.1.11)이 수행되어 런타임에 문자열을 생성합니다.

따라서 첫 번째 표현식의 오른쪽 피연산자는 암시 적으로 문자열로 변환됩니다. string = string + ((char)65) + 5;

그러나 두 번째 표현식의 string += ((char)65) + 5;경우 +=복합 할당 연산자를와 함께 고려해야 +합니다. 이 때문에 +=보다 약한 +제 1, +작업자가 먼저 평가된다. 여기 이진 숫자로 승격char 되는 int있습니다. 그런 다음 평가되지만 현재는 연산자를 포함하는 표현식의 결과 가 이미 평가되었습니다.int+=+


사례 1

string = string +((char)65) + 5;

모든 것이 문자열로 취급되지만 두 번째 경우에는

수행 된 작업 순서 :

  • string +((char)65 = stringA
  • stringA + 5 = stringA5

사례 2

 string += ((char)65) + 5;

첫 번째 오른쪽이 계산된다는 것은 첫 번째 연산이 ((char)65) + 5, 따라서 ((char)65) + 5 is 70+ = 연산의 결과 와 같음을 의미 합니다.

수행 된 작업 순서 :

  • (char)65 + 5 = 70
  • string + 70 = string70

예를 1 개 더 보자

String string = "string";
string += ((char)65) + 5 + "A";
System.out.println(string); 

출력 문자열

이유 동일한 첫 번째 오른쪽이 계산되고 수행 된 작업의 순서가

  • (char)65 + 5 = 70
  • 70 + "A" = 70A
  • string + 70A = string70A

당신이 쓸 때 :

string = string + ((char)65) + 5;

글을 쓰는 것과 같습니다.

String string =
     new StringBuilder(string).append((char)65).append((int)5).toString();

어떤 추가 같다 stringA하고 (65 진수의 문자 표현) 5.

후자의 경우 먼저 오른손을 계산 한 다음 결과를에 추가하면 다음 string과 같이 작성됩니다.

string = string + 70;

string = string +((char)65) + 5;

이 수단 "의 연결로 설정 문자열 string, ((char)65)하고 5." 이것은 왼쪽에서 오른쪽으로 평가됩니다 (먼저 먼저 string + ((char)65), 그다음에 +5, 문자열과 정수의 연결은 그 정수를 문자열로 변환합니다.

string += ((char)65) + 5;

This means "Calculate the result of ((char)65)+5 and add it to string" - the entire right-hand side is evaluated before adding the result to the string. Since a char is really just a 16-bit integer, it adds them together as integers - giving 70 - and then it appends that to string.


It is the same case as the example:

System.out.println("abc"+10 + 5);

produces abc105 (add as String)

and

System.out.println(5 + 10);

produces 15 (add as Number)

The String included in the (first place of the) operation forces all the elements to be treated as Strings while executing the operation. In your case with += however, the operation is executed first in the right part (treating the elements as int) because of the operator precedence and then is concatenated with the String.

ReferenceURL : https://stackoverflow.com/questions/20515911/concatenation-of-strings-and-characters

반응형