Visualizzazione dei risultati da 1 a 4 su 4

Visualizzazione discussione

  1. #4
    Utente di HTML.it L'avatar di andbin
    Registrato dal
    Jan 2006
    residenza
    Italy
    Messaggi
    18,284
    Quote Originariamente inviata da xoth Visualizza il messaggio
    grande! ho capito il mio errore... io le introducevo come variabili di tipo byte non int ma come mai ci vuole 1 minimo di int? immagino con il long quindi
    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.
    Ultima modifica di andbin; 11-09-2016 a 11:40
    Andrea, andbin.devSenior Java developerSCJP 5 (91%) • SCWCD 5 (94%)
    java.util.function Interfaces Cheat SheetJava Versions Cheat Sheet

Permessi di invio

  • Non puoi inserire discussioni
  • Non puoi inserire repliche
  • Non puoi inserire allegati
  • Non puoi modificare i tuoi messaggi
  •  
Powered by vBulletin® Version 4.2.1
Copyright © 2025 vBulletin Solutions, Inc. All rights reserved.