Enter the cast job from int to byte using the final keyword in java

public static void main(String[] args) { final int a =15; byte b = a; System.out.println(a); System.out.println(b); } 

In the above code, when I convert from int to byte, it does not give a compile-time error, but when my conversion is from long to int, it gives a 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); } 
+7
java
source share
1 answer

From the JLS section in assignment conversions :

Also, if the expression is a constant expression of type byte , short , char or int :

  • Narrowing the primitive conversion can be used if the variable type is byte , short or char , and the value of the constant expression is represented in the variable type.

When you declare and initialize your final a , this is an expression of a compile-time constant, and the compiler can determine that a value of 15 will fit safely into the byte . JLS simply does not allow implicit narrowing of conversions from long without explanation, and this rule goes back to at least Java 2 (the earliest JLS I could find anywhere).

I would suggest that this rationale may be due to the fact that Java bytecode is defined for 32-bit word size and that operations on long logically more complex and expensive.

+11
source share

All Articles