The rules for promotion is "when operands are of different types, automatic binary numeric promotion occurs with the smaller operand type being converted to the larger". But the operands are of same type for example,
byte=byte+byte // Compile time error... found int..
So why is it so?
The name Type Promotion specifies that a small size datatype can be promoted to a large size datatype. i.e., an Integer data type can be promoted to long, float, double, etc. This Automatic Type Promotion is done when any method which accepts a higher size data type argument is called with the smaller data type.
Type promotion in C is a method to convert any variable from one datatype to another. C allows variables of different datatypes to be present in a single expression. There are different types of type conversions available in C. They are Implicit type conversion and Explicit type conversion.
Numeric promotion is the conversion of a smaller numeric type to a larger numeric type, so that integer and floating-point operations may take place. In numerical promotion, byte, char, and short values are converted to int values. The int values are also converted to long values, if necessary.
We can convert int to long in java using assignment operator. There is nothing to do extra because lower type can be converted to higher type implicitly. It is also known as implicit type casting or type promotion.
There's no + operator for byte
. Instead, both operands are promoted to int, so you've got
byte = byte + byte ... becomes (widening to find + operator) ... byte = int + int ... becomes (result of + operator) ... byte = int
... which then fails because there's no implicit conversion from int
to byte
. You need to cast:
byte a = 1; byte b = 2; byte c = (byte) (a + b);
Here are the actual rules for numeric promotion, from section 5.6.2 of the JLS:
When an operator applies binary numeric promotion to a pair of operands, each of which must denote a value that is convertible to a numeric type, the following rules apply, in order, using widening conversion (§5.1.2) to convert operands as necessary:
You were provided with correct answer about automatic promotion to 'int'.
There is one more note about that - compound assignment operators behave as they have an implicit type case. Example:
byte b1 = 1; byte b2 = 2; b1 = b1 + b2; // compilation fails b1 += b2; // compilation successful
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With