简体   繁体   中英

Java integer to short conversion rules

In the code, only the first case(integer variable to short) has a compile error (lossy conversion from int to short). Why don't the other cases (integer literal to short and final integer variable to short) have this same compile error?

public class Test
{   
    public static void main(String[] args)
    {
        short shortNum = 0;
        
        //integer variable to short
        int intNum = 12;
        shortNum = intNum;
        
        //integer literal to short
        shortNum = 12;

        //final integer variable to short
        final int finalNum = 12;
        shortNum = finalNum;
    }
}

See the answer as comments:

short shortNum = 0;

//integer variable to short
int intNum = 12;
shortNum = intNum; //doesn't work, because casting primitives is required any time you are going from a larger numerical data type to a smaller numerical data type.
        
//integer literal to short
shortNum = 12; //This is not integer literal per se, you're initializing your short variable with 12, which fits in short data type, so it's short.

//final integer variable to short
final int finalNum = 12; //your variable is final, and according to Java Language Specification, if final variable's value fits into the type you're casting it, then no explicit cast is needed.
shortNum = finalNum;

The answer is in this post: Type cast issue from int to byte using final keyword in java .

If Java knows that the number is a constant and fits in another type, then you can use it.

In the case of a non-constant value, you can't know how the variable will evolve... In this case, for protection, it will not allow a type change.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM