2013-06-17 11 views
5

Ho appena creato un semplice programma java utilizzando il tipo di dati short.
Il programma si presenta così:comportamento imprevisto nei tipi

class test 
{ 
    public static void main(String arg[]) 
    { 
     short x=1; 
     short x_square=x*x; 
    } 
} 

Questo programma genera un errore:

java:6: possible loss of precision 
found : int 
required: short 

Come compilatore fonda int? Non c'è una variabile int in questo programma tutte le variabili sono dichiarate come short.

risposta

11

Durante l'operazione aritmetica, i tipi interi vengono sempre considerati come primitivi int in Java se nessuno di essi è di tipo long. I tipi di interi piccoli vengono promossi a int e il risultato dell'operazione è int. Quindi x*x è inserito nel cast come int e si sta tentando di assegnarlo a short. È necessario un cast esplicito per short per questa conversione di riduzione.

short x_square=(short)(x*x); 

Seguire la JLS 4.2.2

If an integer operator other than a shift operator has at least one operand of type long, then the operation is carried out using 64-bit precision, and the result of the numerical operator is of type long. If the other operand is not long, it is first widened (§5.1.5) to type long by numeric promotion (§5.6).

Otherwise, the operation is carried out using 32-bit precision, and the result of the numerical operator is of type int. If either operand is not an int, it is first widened to type int by numeric promotion.

+0

grazie per il link che mi ha aiutato molto –

4

Da the specification:

If an integer operator other than a shift operator has at least one operand of type long, then the operation is carried out using 64-bit precision, and the result of the numerical operator is of type long. If the other operand is not long, it is first widened (§5.1.5) to type long by numeric promotion (§5.6).

Otherwise, the operation is carried out using 32-bit precision, and the result of the numerical operator is of type int. If either operand is not an int, it is first widened to type int by numeric promotion.

Aggiunta una breve e poco fa un int. Se si desidera memorizzare il risultato in una variabile di tipo int, è necessario eseguirne il cast.

+0

grazie per l'informazione –

2

Prova a trasmettere è: short x_square=(short)(x*x)

+0

grazie per le informazioni –

4

Perché la moltiplicazione di due cortometraggi restituisce un int in Java. Per sbarazzarsi di questo errore è necessario disporre di tipo esplicito casting:

short x_square=(short)x*x; 

In alternativa, è anche possibile effettuare le seguenti operazioni:

short x_square = x; 
x_square *= x_square; 
+0

grazie per l'informazione –

Problemi correlati