IT

왜“short thirty = 3 * 10”이 법적 과제입니까?

lottoking 2020. 8. 19. 18:52
반응형

왜“short thirty = 3 * 10”이 법적 과제입니까?


경우 short자동으로 승격되어 산술 int연산에서, 왜이다 :

short thirty = 10 * 3;

short변수에 대한 법적 할당 thirty?

차례로 이것은 :

short ten = 10;
short three = 3;
short thirty = ten * three; // DOES NOT COMPILE AS EXPECTED

뿐만 아니라 :

int ten = 10;
int three = 3;
short thirty = ten * three; // DOES NOT COMPILE AS EXPECTED

예상대로 캐스팅하지 않고 int값을 할당 할 수 없기 때문에 short.

숫자 리터럴에 대해 특별한 일이 있습니까?


컴파일러는 타임에10*3 30으로 대체되기 때문 입니다. 그렇게하는 것은 short thirty = 10 * 3시간에 계산됩니다.

변경 시도 tenthreefinal short(그들에게 수단 시간 상수을) 어떻게 조치 : P를

javap -v두 버전 ( 10*3final short)에 대해 사용하여 바이트 코드를 검사 합니다. 차이가 거의 없습니다.

자, 여기에 다른 경우에 대한 바이트 코드 차이가 있습니다.

사례 -1 :

자바 코드 : main () {short s = 10 * 3; }

바이트 코드 :

stack=1, locals=2, args_size=1
         0: bipush        30  // directly push 30 into "s"
         2: istore_1      
         3: return   

사례 -2 :

public static void main(String arf[])  {
   final short s1= 10;
   final short s2 = 3;
   short s = s1*s2;
}

바이트 코드 :

  stack=1, locals=4, args_size=1
         0: bipush        10
         2: istore_1      
         3: iconst_3      
         4: istore_2      
         5: bipush        30 // AGAIN, push 30 directly into "s"
         7: istore_3      
         8: return   

사례 -3 :

public static void main(String arf[]) throws Exception {
     short s1= 10;
     short s2 = 3;
     int s = s1*s2;
}

바이트 코드 :

stack=2, locals=4, args_size=1
         0: bipush        10  // push constant 10
         2: istore_1      
         3: iconst_3        // use constant 3 
         4: istore_2      
         5: iload_1       
         6: iload_2       
         7: imul          
         8: istore_3      
         9: return 

위의 경우, 103로컬 변수에서 촬영 s1s2


예, 리터럴 케이스에 특별한 일 10 * 3이 있습니다 . 컴파일 타임에 평가됩니다 . 따라서 (short)곱한 리터럴에 대한 명시 적 변환이 필요하지 않습니다 .

ten * three 명시 적 변환이 필요합니다.

tenthree표시되는 경우 다른 문제가 발생 final합니다.


다음 답변 은 JLS 섹션과이 동작에 대한 세부 정보를 추가합니다.

당으로 §15.2 JLS - 표현의 양식

일부 식에는 컴파일 타임에 확인할 수있는 값이 있습니다. 이들은 상수 표현식입니다 (§15.28).

참고 URL : https://stackoverflow.com/questions/32203462/why-is-short-thirty-3-10-a-legal-assignment

반응형