How compile time constant will work internally in java

user9018479 :

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;
Crummy :

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.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=13989&siteId=1