How compile time constant will work internally in java

本小妞迷上赌 提交于 2020-03-23 14:33:15

问题


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:


This is because not all ints will fit into a byte.

In your first example, the value of a is known and cannot change. The compiler knows that it will fit into a byte.

In your second example, because a is not final, it's possible that it could have been changed (though not in your example). The Java compiler isn't smart enough to notice that nothing has changed it, so it's no longer certain that it will fit into a byte.

As an example, take a look at this:

    final int a = 10000;
    byte b = a;

Because the value of a is now too big to fit into an int, it no longer compiles.




回答2:


In below case when your int value is not final,you have to cast int to byte while assigning an integer value to byte in java.

int a=11;
byte b= (byte) a;


来源:https://stackoverflow.com/questions/60445385/how-compile-time-constant-will-work-internally-in-java

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!