2013-10-16 2 views
0

을 두배로 승격되지왜 내 데이터 형식이 자동으로 I는 데이터 유형이 자동으로 짧은 INT 바이트 상위 데이터 유형으로 승진 것을 알고

class Temp { 
    void check(byte x) { 
     System.out.println(x + " is the byte type"); 
    } 

    void check(short x) { 
     System.out.println(x + " is the short type"); 
    } 

    void check(int x) { 
     System.out.println(x + " is the int type"); 
     int y = x; 
     System.out.println(y + " is the int type"); 
    } 

    void check(long x) { 
     System.out.println(x + " is the long type"); 
    } 

    void check(float x) { 
     System.out.println(x + " is the float type"); 
    } 

    void check(double x) { 
     System.out.println(x + " is the double type"); 
    } 

    public static void main(String args[]) { 
     byte b = 42; 
     char c = 'a'; 
     short s = 1024; 
     int i = 50000; 
     float f = 5.67f; 
     double d = .1234; 
     double result = (f * b) + (i/c) - (d * s); 
     System.out.println((f * b) + " + " + (i/c) + " - " + (d * s)); 
     System.out.println("result =" + result); 
     Temp t = new Temp(); 
     t.check(f * b); 
     t.check(i/c); 
     t.check(d * s); 
     t.check(b + b); 
     t.check(b * b); 
     t.check(b * b * b); 
     t.check(b * b * b * b * b * b * b * b * b); 
     t.check(b * b * b * b * b * b * b * b * b * b * b * b * b * b * b * b 
       * b * b * b * b * b * b * b * b * b * b * b * b * b * b * b); 
     t.check(b * b * b * b * b * b * b * b * b * b * b * b * b * b * b * b 
       * b * b * b * b * b * b * b * b * b * b * b * b * b * b * b * b 
       * b * b * b * b * b); 

    } 
} 

출력 :

238.14 + 515 - 126.3616 
result =626.7784146484375 
238.14 is the float type 
515 is the int type 
515 is the int type 
126.3616 is the double type 
84 is the int type 
84 is the int type 
1764 is the int type 
1764 is the int type 
74088 is the int type 
74088 is the int type 
-1889539584 is the int type 
-1889539584 is the int type 
-2147483648 is the int type 
-2147483648 is the int type 
0 is the int type 
0 is the int type 

내 질문은 42 * 42 = 84이고 바이트 범위가 -128 ~ 127이기 때문에 b * b가 int로 승격시키는 이유입니다. 84가 범위 내에 있습니다. 또한, 이유는

t.check(b * b * b * b * b * b * b * b * b * b * b * b * b * b * b * b 
       * b * b * b * b * b * b * b * b * b * b * b * b * b * b * b); 

이 줄을 가지고있어 왜 두 배로 홍보하지.

+0

"왜 b * b가 int로 승격되는지"- 그렇지 않습니다. 그것은 승진 된'b'입니다. –

답변

5

제 질문은 왜 ㄱ * B는 그 언어 사양이 할 것이라고 말했습니다 무엇 때문에

을 int로 추진한다는 것이다. 그 언어가 정의되어 있지 방법 때문에

왜 [...]이 줄을 가지고 0 왜, 다시 두 배

에 홍보하지.

읽기 section 15.17 of the JLS :

곱셈 연산자는 우선 순위가 동일하고 구문 왼쪽 연관있다 (그들은 그룹을 왼쪽에서 오른쪽으로).

곱셈 연산자의 각 피연산자 유형은 원시 숫자 유형으로 변환 할 수있는 유형 (§5.1.8)이어야하며 그렇지 않으면 컴파일 타임 오류가 발생합니다.

2 진 수치 승격이 피연산자 (§5.6.2)에 대해 수행됩니다.

이진 숫자 프로모션 (5.6.2는) intbyte 피연산자를 촉진 할 것이다, 그래서 당신은 당신의 코드에서 모든 경우에 int * int 산술와 끝까지. 첫 번째 경우에는 byte * byte이 있으므로 두 피연산자는 모두 int으로 승격됩니다. 긴 줄에는 byte * byte이 있고 나머지는 int * byte입니다. 두 번째 피연산자는 int으로 승격됩니다. 이 선택은 컴파일 타임에 이루어지며 실행시의 값과는 아무런 관련이 없습니다. JVM은 int의 범위를 오버플로하기 때문에 값을 double으로 승격 시키려고 결정하지 않습니다.

관련 문제