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);
}
The byteValue() method of Integer class of java. lang package converts the given Integer into a byte after a narrowing primitive conversion and returns it (value of integer object as a byte).
An int value can be converted into bytes by using the method int. to_bytes().
Type casting is when you assign a value of one primitive data type to another type. In Java, there are two types of casting: Widening Casting (automatically) - converting a smaller type to a larger type size. byte -> short -> char -> int -> long -> float -> double.
From the JLS section on assignment conversions:
In addition, if the expression is a constant expression of type
byte
,short
,char
, orint
:
- A narrowing primitive conversion may be used if the type of the variable is
byte
,short
, orchar
, 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.
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