Promotion and conversion in java

Jayesh Sonkusare :

Promotion means to promote or convert the smaller type literals to a higher type. This promotion is used in evaluating expressions. Now I have a doubt regarding this. When i type this statement

byte var1 = 56 + 10;

Gives the answer 66. How can this be possible? According to the promotion rules, every byte, short and char is promoted to int. So this 56 and 10 would be promoted to int and hence the answer 66 would be in int. This 66 would be then stored in a variable of byte type. However to store something from int to byte, casting is to be done. But this code works perfectly without casting.

Ruelos Joel :

This is okay because you are giving constant value. See compile-time narrowing of constants.

The compile-time narrowing of constants means that code such as:

byte theAnswer = 42;

is allowed. Without the narrowing, the fact that the integer literal 42 has type int would mean that a cast to byte would be required:

byte theAnswer = (byte) 42; // cast is permitted but not required

Guess you like

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