java基础----一些疑惑

来源:互联网 发布:数据合理性分析 编辑:程序博客网 时间:2024/06/10 07:39

一:先看看这段代码

下面代码可以编译通过

public class TestMath{    public static void main(String[] args)    {       short a = 6 + 6;    }}
查看其字节码

public static void main(java.lang.String[])    code:    0:    bipush   12    2:    istore_1    3:  return


二:再看看这段代码
但是short b = 6;short c = 6;short a = b + c;就编译失败了。需要改成short a = (short)(b + c)

public class TestMath{    public static void main(String[] args)    {        short b = 6;        short c = 6;        short a = (short)(b + c);    }}

查看字节码

public static void main(java.lang.String[])    code:    0:    bipush   6    2:    istore_1    3:    bipush   6    5:    istore_2    6:    iload_1    7:    iload_2    8:    iadd    9:    i2s    10:  istore_3    11:  return


三:现在再看看这段代码

short a = 

public class TestMath{    public static void main(String[] args)    {       short a = (short)6;       short b = (short)6;    }}
查看字节码

public static void main(java.lang.String[])    code:    0:    bipush   6    2:    istore_1    3:    bipush   6    5:    istore_2    6:    iload_1    7:    iload_2
可知,即使是转型为short,在内存中还是以int来存储。所以short c = a + b;编译失败;short c = (short)a + (short)b;也是编译失败。


通过查看字节码可知,对应长度比int短的数据类型(byte,char,short),他们进行数学运算时,在内存中是当成int看待的。

所以,运算之前,b和c以int身份载入栈中,(b + c)的结果是一个int型,如果把它赋给一个short型,需要转型。

而对于short a= 6 + 6;等号后面的东西没有变量,都是常量,在编译器,就进行了运算变成了常量12。这个是一个int型,也当成了int型保存了,所以不需要转换

注意:

由上可知:short a = (int)6 + 6;或者char a = (short)6 + 6;也是可以编译通过的。这种常量的赋值都没问题。但是short a = 6;byte b = a;就不行了。(注意 byte又有点特殊了,超过127的直接量赋值给他的话,都会有编译错误)

但是:short a = 6l + 6;就无法编译通过了,因为6l表示一个long型的6,后面的6是int型,编译器运算得出long型的12,他必须要转成int或者更低位,才可以。


原创粉丝点击