Search code examples
javavariablestype-conversionliteralstype-promotion

How numeric promotion and demotion works for literals and variables in Java?


I'm not sure if my question is clear enough, so I will give examples. Let's think we have the next expression:

byte byteNumber = 10 * 10;

I understand the literal number 10 is an integer by default, so the expression 10 * 10 also results in an integer, BUT Java "demotes" it to a byte value since the variable (where the result is stored) is a byte.

However, why this works different?

int x = 10;
int y = 10;

byte byteNumber = x * y;

The line byte byteNumber = x * y; is marked as an error. I understand the expression x * y results in an integer but is not "demoted" as with the literals. Even if there is only one variable, like x * 10, the result won't be demoted. Why exactly? I believe it has something to do with the variables type, but literals are integers by default and they can get "demoted".

Another example I am struggling with is: we can assign integers literals to variables of type byte, short or char, and Java will automatically convert the integer into the type of variable we have declared, like:

short a = 10;
byte b = 12;

On the other hand, why can't we do something like this?

float c = 12.0;

Yes, 12.0 is a double, but why can't it be "demoted" to float and forces us to declare the literal as a float 12.0F? I understand this would represent a lose of information. However, converting an integer to a short or byte also represents a lose of information, isn't it?

Finally, why can we assign a integer literal to a variable of type short or byte...

 short a = 10;
 byte b = 12;

but we cannot pass an integer as argument to a method that expects a short/byte parameter?

public void newMethod(short x, byte y){
    ...
}

. . .

newMethod(10, 2)

It would be great if you could search some links where I can read this kind of stuff (since I'm not really sure how to search for these specific issues I have).

Thank you all in advance.


Solution

  • You could check the following two links out:

    By the way, both of those questions were answered by the #1 StackOverflow contributor Jon Skeet :)