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.
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
toshort
,int
,long
,float
, ordouble
- ...
Note the lack of char
in the list of target types for conversions from byte
.
See more on this question at Stackoverflow