No alt. L'operatore di NOT bitwise ( ~ ) è usabile anche con i tipi inferiori al int (byte, short, char). La questione è che nell'uso degli operatori viene applicata la numeric promotion, sia per gli operatori binari (cioè con 2 operandi), sia unari (con 1 operando, come ~ ).
Esiste quindi la binary numeric promotion e la unary numeric promotion.
La binary numeric promotion si basa su 4 punti, che sul Java Language Specification sono detti così:
• If either operand is of type double, the other is converted to double.
• Otherwise, if either operand is of type float, the other is converted to float.
• Otherwise, if either operand is of type long, the other is converted to long.
• Otherwise, both operands are converted to type int.
Il minimo a cui vengono portati gli operandi è int! Quindi:
un byte + un int ---> int
un int + un long ---> long
un double + un short ---> double
Ma attenzione:
un byte + un byte ---> int (non byte!)
un byte + un short ---> int (non short!)
Idem per gli altri operatori binari - * / % ecc...
La stessa cosa, in modo limitato ad 1 operando, vale per gli operatori unari come ~ .
byte b = 10;
byte b2 = ~b; // ERRORE, il risultato è un int che NON può andare direttamente in un byte
Serve un cast:
byte b2 = (byte) ~b; // OK
La numeric promotion è importantissima, fissala bene nella mente.![]()