While Boann's answer is correct, there is a complication that applies to the case of constant expressions when they appear in assignment contexts.
Consider the following examples:
char x;
x = 'a' + 'b'; // OK
char y = 'a';
ychar z = y + 'b'; // Compilation error
What is going on? They mean the same thing don't they? And why is it legal to assign an int to a char in the first example?
When a constant expression appears in an assignment context, the Java compiler computes the value of the expression and sees if it is in the range of the type that you are assigning to. If it is, then an implicit narrowing primitive conversion is applied.
In the first example,
'a' + 'b'is a constant expression, and its value will fit in achar, so the compiler allows the implicit narrowing of theintexpression result to achar.In the second example,
yis a variable soy + 'b'is NOT a constant expression. So even though Blind Freddy can see that the value will fit, the compiler does NOT allow any implicit narrowing, and you get a compilation error saying that anintcannot be assigned to achar.
There are some other caveats on when an implicit narrowing primitive conversion is allowed in this context; see JLS 5.2 and JLS 15.28 for the full details. The
The latter explains in detail the requirements for a constant expression. It may not be what you may think. (For example, just declaring y as final doesn't help.)