简体   繁体   中英

Why can't I assign a final long to an int?

As far as I understand, variable evaluation is done at run time. However, type evaluation is done at compile time in Java.

Also as I see, making a variable constant (I am using local variables but it changes nothing about the concept above), will make its value known at compile time.

I provide you two examples to test this concept. The first is working and the second is not.

Could someone explain to me why making the variable constant allows me to assign a short variable to an int variable, whereas I cannot assign an int variable to a long?

// Working example
final int x = 10;
short y = x;

// Non-working example
final long a = 10L;
int b = a;

The relevant part of the language spec is JLS 5.2, Assignment Contexts :

In addition, if the expression is a constant expression (§15.28) of type byte, short, char, or int:

  • A narrowing primitive conversion may be used if the variable is of type byte, short, or char, and the value of the constant expression is representable in the type of the variable.

Making the a and x variables final makes them constant expressions (because they're initialized with constant values too).

The first example works because x is a constant int that you're trying to assign to a short variable, and the value is representable in a short ; the second example doesn't because x is a constant long , and you're trying to assign it to an int variable (the value is representable, but this doesn't matter because it is already disqualified from implicit narrowing conversion).

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