Type cast issue from int to byte using final keyword in java
java
Solution
From the JLS section on assignment conversions:
In addition, if the expression is a constant expression of type `byte`, `short`, `char`, or `int`:
- A narrowing primitive conversion may be used if the type of the variable is `byte`, `short`, or `char`, and the value of the constant expression is representable in the type of the variable.
When you're declaring and initializing your `final a` , that's a compile-time constant expression, and the compiler can determine that the value `15` will safely fit in a `byte`. The JLS simply does not permit implicit narrowing conversions from `long`, without explanation, and this rule goes back to at least Java 2 (the earliest JLS I could find anywhere).
I would speculate that that rationale may stem from the fact that the Java bytecode is defined for a 32-bit word size and that operations on a `long` are logically more complicated and expensive.
Problem
``` public static void main(String[] args) { final int a =15; byte b = a; System.out.println(a); System.out.println(b); } ``` In above code when I am converting from int to byte it is not giving compile time error but when my conversion is from long to int it is giving compile time error, WHY? ``` public static void main(String[] args) { final long a =15; int b = a; System.out.println(a); System.out.println(b); } ```