Java程序在一行中进行多种类型转换 [英] Multiple typecasting in a single line in Java program

查看:76
本文介绍了Java程序在一行中进行多种类型转换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

今天,在弄乱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?

推荐答案

基本上,它只是一连串的类型转换和一元 + -

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 ,这是一个不断扩大的原始转换。请参见 JLS第5章:转化和促销

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


原始类型的19种特定转换称为扩展原始转换:

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


  • 以字节为单位的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程序在一行中进行多种类型转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆