Question

Can the variable below (called b) be called an expression, if it is the only thing located to right of the equals sign?

// This code fragment will not compile.
// c is a char, and b is a byte.

c = b;

The reason why I ask this question is because of the topic of type promotion within expressions. I understand that Java promotes all bytes to ints. Is that the only reason why this code fragment does not compile? (Please note that I know about casts; that's not the point of this thread. Thanks a lot.)

Edit: Thanks a lot Jon and Peter. Looking at this topic using a second example:

byte b = 1;
short s = 2;

s = b;  // OK
s = b*2;  // Not OK (compilation error)

Is it true that the following is happening?

(Line 3) Java converts the byte to short. (Line 4) Java converts the expression b*2 to an int.

If this is correct, then it would seem that =b; and =b*2; are "expressions" that Java handles differently. So, the =b; "expression" is not converted to an int, but widened to a short. But the =b*2; expression is converted to an int, and not to a short, even though the target variable called s is a short.

Edit 2: Also -

short s1, s2 = 2, s3 = 2;
s1 = s2*s3;  // Not OK (compilation error)

Even though all three variables are shorts, the s2*s3; expression is promoted to an int, and thus causes a compilation error.

Was it helpful?

Solution 2

Can the variable below (called b) be called an expression, if it is the only thing located to right of the equals sign?

Yes, absolutely.

I understand that Java promotes all bytes to ints.

Well, in some cases. Not in all cases.

Fundamentally the code doesn't compile because there's no implicit conversion from byte to char. From section 5.1.2 of the JLS (widening primitive conversions):

19 specific conversions on primitive types are called the widening primitive conversions:

  • byte to short, int, long, float, or double
  • ...

Note the lack of char in the list of target types for conversions from byte.

OTHER TIPS

Try this

byte b = -1;
short s = b; // is ok as a byte can be promoted to an short.
int i = b; // is ok as a byte can be promoted to an int.
float f = b; // is ok as a byte can be promoted to an float, long or double.

char c = b; // won't compile

but

final byte b = 1;
char c = b; // compiles fine as the compiler can inline the value.

In this case

short s = b*2;  // Not OK (compilation error)

b * 2 is an int as 2 is an int value. If b were final you would be able to do this was the compile can inline the value.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top