Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Type cast issue from int to byte using final keyword in java

Tags:

java

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);
}
like image 459
Shashank Agarwal Avatar asked Jul 12 '14 20:07

Shashank Agarwal


People also ask

Can I convert int to byte in Java?

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).

How do you convert int to bytes?

An int value can be converted into bytes by using the method int. to_bytes().

What is type casting in Java explain with example?

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.


1 Answers

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.

like image 194
chrylis -cautiouslyoptimistic- Avatar answered Oct 23 '22 06:10

chrylis -cautiouslyoptimistic-