问题描述
今天,在弄乱Java语法时,我尝试编译以下Java代码:
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);
}
}
该代码实际上没有编译或运行时错误。将 i
的数据类型更改为任何其他数据类型,例如 int
或 double
或 char
也可以。不仅如此,在声明中引入操作也没有任何错误:
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;
当我在Netbeans中使用自动格式设置代码格式时,上述声明的格式如下:
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?
推荐答案
基本上,它只是一连串的类型转换和一元 +
和-$ c
It's basically just a chain of casts and unary +
and -
.
float i = (char) +(int) -(long) (byte) 100;
相当于
byte tmp1 = (byte) 100;
long tmp2 = (long) tmp1;
long tmp3 = -tmp2;
int tmp4 = (int) tmp3;
int tmp5 = +tmp4;
char tmp6 = tmp5;
float i = tmp6;
最后的任务是从 char
到 float
,这是一个不断扩大的原始转换。请参见
The final assignment is from char
to float
, which is a widening primitive conversion. See JLS Chapter 5: Conversions and Promotions
- 以字节为单位的short,int,long,float或double
- 以short到int,类型,long,float或double
- 字符转换为整型,整型,浮点型或双精度型
- int转换为整型,浮点型或双精度型
- 可浮动或加倍
- 可浮动可加倍
- 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
这篇关于Java程序在一行中进行多种类型转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!