编译时间常数将如何在Java内部运行 [英] How compile time constant will work internally in java

查看:70
本文介绍了编译时间常数将如何在Java内部运行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的问题是编译时间常数在内部如何工作,因此我们在Lower语句中没有收到错误。

My question is how compile time constant works internally so we didn't get an error in Below statement.

final int a = 10;
byte b = a;

为什么我在此语句中出现错误。

And why am I getting error in this statement.

int a = 10;
byte b = a;


推荐答案

1。对于二元运算符('='或'+'...),则编译器使用数字提升系统。这会在执行操作之前提升原始类型,使其小于 int(例如字节char),并缩短为 int。

1.For a binary operator ( '=' or '+'... ), the compiler uses a numeric promotion system. This promotes a "primitive type" lower than "int" like byte char and short to an "int" before performing the operation.

2. 然后,byte,char,short接受一个恒定的int值,该值适合其类型大小。

所以下面将进行编译:

    final int int1 = 10;
    byte byt1 = int1; /* int to byte and when compiling to bytecode byt1 is assigned 10 and not a variable int1 as it's a final constant.*/

这将不会编译:

    byte byt1 = 2;
    byte byt2 = +byt1; /* int to byte but when compiling to bytecode byt1 is not assigned 2 as byt1 value might change at run time to a value larger than what byte can support so you get compiler error.*/

,并且不会编译:

    final long lng1 = 10;
    byte byt2 = lng1; /* long type to byte. remember byte, char and short only accept int.*/

这篇关于编译时间常数将如何在Java内部运行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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