Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple typecasting in a single line in Java program

While messing around with Java syntax today, I tried to compile the following piece of java code:

class Mess {
    public static void main(String[] args) {
        float i = (char)(int)(long)(byte) 100;
        System.out.println(i);
    }
}

The code actually gave no compilation or runtime errors. Changing data type of i to any other data type like int or double or char also worked. Not only this, introducing operations in the declaration also worked without any errors:

float i = (char)+(int)-(long)(byte) 100;

When I used auto-format in Netbeans to format the code, the above declaration was formatted as follows:

float i = (char) +(int) -(long) (byte) 100;

Please help me in understanding how this code is compiled?

like image 445
Bhoot Avatar asked May 01 '15 11:05

Bhoot


1 Answers

It's basically just a chain of casts and unary + and -.

float i = (char) +(int) -(long) (byte) 100;

It's equivalent to

byte tmp1 = (byte) 100;
long tmp2 = (long) tmp1;
long tmp3 = -tmp2;
int  tmp4 = (int) tmp3;
int  tmp5 = +tmp4;
char tmp6 = tmp5;
float i = tmp6;

The final assignment is from char to float, which is a widening primitive conversion. See JLS Chapter 5: Conversions and Promotions

19 specific conversions on primitive types are called the widening primitive conversions:

  • byte to short, int, long, float, or double
  • short to int, long, float, or double
  • char to int, long, float, or double
  • int to long, float, or double
  • long to float or double
  • float to double
like image 53
aioobe Avatar answered Nov 16 '22 11:11

aioobe