简体   繁体   中英

How compile time constant will work internally in java

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;

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.

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;

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. Then byte, char, short, accept an int value that is constant and fits their type size.

so the below will Compile :

    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.*/

this will not compile :

    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.*/

and this will not compile :

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM