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;
Yes, It will work in that case. because the fourth multiplication with i takes it beyond Integer. MaxValue . So both approach will work.
Yes, you can add a long and an int just fine, and you'll end up with a long . The int undergoes a widening primitive conversion, as described in the Java Language Specification, specifically JLS8, §5.1.
You cannot change the value of final int because Java uses the keyword 'final' for declaring constants & if you try to modify it then the compiler will generate error !
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With