Development Tip

Java에서 두 문자를 추가 한 결과는 int 또는 char입니까?

yourdevel 2020. 10. 23. 19:09
반응형

Java에서 두 문자를 추가 한 결과는 int 또는 char입니까?


추가 할 때 'a' + 'b'그것은 195은 출력 데이터 형이며, 생산 char또는 int?


Java 문자, 단락 또는 바이트를 추가 한 결과는 int입니다 .

이진 숫자 프로모션에 대한 Java 언어 사양 :

  • 피연산자 중 하나라도 참조 형식이면 unboxing 변환 (§5.1.8)이 수행됩니다. 그때:
  • 피연산자가 double 유형이면 다른 피연산자가 double로 변환됩니다.
  • 그렇지 않으면 피연산자가 float 유형이면 다른 피연산자가 float로 변환됩니다.
  • 그렇지 않고 피연산자 중 하나가 long 유형이면 다른 피연산자가 long으로 변환됩니다.
  • 그렇지 않으면 두 피연산자가 모두 int 유형으로 변환됩니다.

그러나 복합 할당 연산자 (예 : + =)에 대한 내용에 유의하십시오 .

이진 연산의 결과는 왼쪽 변수 ...의 유형으로 변환되고 변환 결과는 변수에 저장됩니다.

예를 들면 :

char x = 1, y = 2;
x = x + y; // compile error: "possible loss of precision (found int, required char)"
x = (char)(x + y); // explicit cast back to char; OK
x += y; // compound operation-assignment; also OK

일반적으로 결과의 유형을 찾을 수있는 한 가지 방법은이를 Object로 캐스트하고 어떤 클래스인지 물어 보는 것입니다.

System.out.println(((Object)('a' + 'b')).getClass());
// outputs: class java.lang.Integer

성능에 관심이있는 경우 Java 바이트 코드 에는 더 작은 데이터 유형을 사용하는 산술 전용 명령조차 없습니다. 예를 들어, 추가의 경우 iadd(int의 경우), ladd(longs의 경우), fadd(float의 경우), dadd(doubles의 경우) 명령어 가 있습니다. x += y더 작은 유형으로 시뮬레이션하기 위해 컴파일러는 ( "int to char") iadd와 같은 명령어를 사용하여 int의 상위 바이트를 사용 하고 0으로 i2c만듭니다. 네이티브 CPU에 1 바이트 또는 2 바이트 데이터에 대한 전용 명령이있는 경우 런타임에이를 최적화하는 것은 Java 가상 머신에 달려 있습니다.

문자를 숫자 유형으로 해석하지 않고 문자열로 연결하려는 경우 여러 가지 방법이 있습니다. 가장 쉬운 방법은 식에 빈 문자열을 추가하는 것입니다. char 및 문자열을 추가하면 문자열이 생성되기 때문입니다. 이러한 모든 표현식의 결과는 String입니다 "ab".

  • 'a' + "" + 'b'
  • "" + 'a' + 'b'(이것은 "" + 'a'먼저 평가 되기 때문에 작동 합니다. ""이 대신 끝에 있으면 얻을 것입니다 "195")
  • new String(new char[] { 'a', 'b' })
  • new StringBuilder().append('a').append('b').toString()
  • String.format("%c%c", 'a', 'b')

charbyte(및 short) 승격 에 대한 이진 산술 연산 int-JLS 5.6.2.


에 대한 다음 표현을 배우고 싶을 수 있습니다 char.

char c='A';
int i=c+1;

System.out.println("i = "+i);

이것은 Java에서 완벽하게 유효하며 66의 문자 (유니 코드)의 해당 값인을 반환합니다 c+1.


String temp="";
temp+=c;
System.out.println("temp = "+temp);

이것은 Java에서 너무 유효하며 String 유형 변수는 temp자동으로 cchar 유형을 허용 temp=A하고 콘솔에서 생성 합니다.


다음 명령문은 모두 Java에서도 유효합니다!

Integer intType=new Integer(c);
System.out.println("intType = "+intType);

Double  doubleType=new Double(c);
System.out.println("doubleType = "+doubleType);

Float floatType=new Float(c);
System.out.println("floatType = "+floatType);

BigDecimal decimalType=new BigDecimal(c);
System.out.println("decimalType = "+decimalType);

Long longType=new Long(c);
System.out.println("longType = "+longType);

c은 유형 이지만 char각 생성자에서 오류없이 제공 될 수 있으며 위의 모든 문은 유효한 문으로 처리됩니다. 그들은 각각 다음과 같은 출력을 생성합니다.

intType = 65
doubleType = 65.0
floatType = 65.0
decimalType = 65
longType =65

char원시 숫자 정수 유형이므로 변환 및 승진을 포함하여 이러한 짐승의 모든 규칙의 적용을받습니다. 이에 대해 읽어보고 싶을 것이며 JLS는 이에 대한 최고의 소스 중 하나입니다 : 전환 및 프로모션 . 특히 "5.1.2 Widening Primitive Conversion"에 대한 짧은 내용을 읽어보십시오.


Java 컴파일러는이를 둘 중 하나로 해석 할 수 있습니다.

프로그램을 작성하고 컴파일러 오류를 찾아서 확인하십시오.

public static void main(String[] args) {
    int result1 = 'a' + 'b';
    char result2 = 'a' + 'b';
}

그것이 문자라면, 첫 번째 줄은 나에게 오류를주고 두 번째 줄은 그렇지 않을 것입니다. int이면 반대가 발생합니다.

나는 그것을 컴파일하고 나는 ..... 오류가 없습니다. 따라서 Java는 둘 다 허용합니다.

그러나 인쇄했을 때 다음을 얻었습니다.

정수 : 195

문자 : Ã

당신이 할 때 일어나는 일은 다음과 같습니다.

char result2 = 'a' + 'b'

암시 적 변환이 수행됩니다 ( int 에서 char 로의 "원시 축소 변환" ).


이진 승격 규칙 에 따르면 피연산자가 double, float 또는 long이 아니면 둘 다 int로 승격됩니다. 그러나 나는 char 유형을 숫자로 취급하는 것에 대해 강력하게 조언합니다.


While you have the correct answer already (referenced in the JLS), here's a bit of code to verify that you get an int when adding two chars.

public class CharAdditionTest
{
    public static void main(String args[])
    {
        char a = 'a';
        char b = 'b';

        Object obj = a + b;
        System.out.println(obj.getClass().getName());
    }
}

The output is

java.lang.Integer


char is represented as Unicode values and where Unicode values are represented by \u followed by Hexadecimal values.

As any arithmetic operation on char values promoted to int , so the result of 'a' + 'b' is calculated as

1.) Apply the Unicode values on corresponding char using Unicode Table

2.) Apply the Hexadecimal to Decimal conversion and then perform the operation on Decimal values.

    char        Unicode      Decimal
     a           0061          97
     b           0062          98  +
                              195

Unicode To Decimal Converter

Example

0061

(0*163) + (0*162) + (6*161) + (1*160)

(0*4096) + (0*256) + (6*16) + (1*1)

0 + 0 + 96 + 1 = 97

0062

(0*163) + (0*162) + (6*161) + (2*160)

(0*4096) + (0*256) + (6*16) + (2*1)

0 + 0 + 96 + 2 = 98

Hence 97 + 98 = 195


Example 2

char        Unicode      Decimal
 Ջ           054b         1355
 À           00c0          192 
                      --------
                          1547    +
                          1163    -
                             7    /
                        260160    *
                            11    %

Here's something strange, though. The following compiles:

char x;
x = 'a' + 'b';

But this does not:

char x;
x = 'a';
x = x + 'b';

It would appear that both expressions ('a'+'b' and x+'b') result in integers, by the following test:

Object obj = 'a'+'b';
System.out.println(obj.getClass().getName());

char x = 'a';
Object obj2 = x+'b';
System.out.println(obj2.getClass().getName());

So why would the second case not compile? Incidentally, you can fix it by casting the entire expression as a char:

x = (char)(x+'b');

This seems like an inconsistency in the semantics of Java - any char expression ought to be interchangeable with another in any context. Does anyone know of a way to make sense of this?

참고URL : https://stackoverflow.com/questions/8688668/in-java-is-the-result-of-the-addition-of-two-chars-an-int-or-a-char

반응형