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?
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
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