What is numeric promotion?
5.6 Numeric Promotions in JLS:
Numeric promotion is applied to the operands of an arithmetic operator. Numeric promotion contexts allow the use of an identity conversion or a widening primitive conversion, or an unboxing conversion.
Numeric promotions are used to convert the operands of a numeric operator to a common type so that an operation can be performed. The two kinds of numeric promotion are unary numeric promotion and binary numeric promotion.
Example of unary numeric promotion produces compile error:
byte b = 15; // assign byte value
byte b1 = +b; // result int but required byte. Compiler error
This is covered by "if the operand is of compile-time type byte, short, or char, unary numeric promotion promotes it to a value of type int" by a widening conversion". You must explicit cast the value to byte type.
Examples of Binary Numeric Promotion produces compile-errors:
// result int can not assign to variable's byte
// (covered by "both operands are converted to type int")
byte = byte + byte;
// result float can not assign to variable's int
// (covered by "if either operand is of type float, the other is converted
// to float")
int = float + int;
// result float can not assign to variable's long
// (covered by "if either operand is of type float, the other is converted
// to float")
long = float + long;
// result double can not assign to variable's float
// (covered by "If either operand is of type double, the other is converted
// to double")
float = double + float;
Most Recent java Faqs
- How to avoid an java.util.ConcurrentModificationException with ArrayList?
- How to convert a given array to a list in Java?
- How to make Java objects eligible for garbage collection?
- What are local variables in Java?
- What are instance variables in Java?
- How many backslashes?
- What are class variables in Java?
Most Viewed java Faqs
- How to use HttpURLConnection POST data to web server?(24745)
- What is runtime polymorphism in Java?(18323)
- How to add BASIC Authentication into HttpURLConnection?(16080)
- What is String literal pool?(14754)
- Can the run() method be called directly to start a thread?(13988)
- What does Class.forname method do?(10593)
- Can transient variables be declared as 'final' or 'static'?(10445)