What Are The Rules For Primitive Arithmetic Promotion Conversion

: For Unary operators

If operant is byte, short or a char it is converted to an int. If it is any other type it is not

converted.

In Java, primitive arithmetic promotion conversion follows a set of rules to determine the type of the result when performing operations on primitive data types. The rules are designed to ensure that there is no loss of precision during the calculations. Here are the rules:

  1. If two values have different data types:
    • The smaller data type is promoted to the larger data type.
    • If one of the operands is double, the other is converted to double.
    • If one of the operands is float, the other is converted to float.
    • If one of the operands is long, the other is converted to long.
    • For all other cases, both operands are converted to int.
  2. Binary numeric promotion:
    • If the operands are of different data types, binary numeric promotion applies.
    • If one operand is double, the other is converted to double.
    • If one operand is float, the other is converted to float.
    • If one operand is long, the other is converted to long.
    • If any of the operands is int, the other is converted to int.
  3. Unary numeric promotion:
    • If the operand is of type byte, short, or char, it is promoted to int before any other operation.

Here are some examples to illustrate these rules:

java
int x = 5;
long y = 10L;
float z = 3.5f;
// Example 1:
long result1 = x + y; // x is promoted to long before addition// Example 2:
float result2 = x * z; // x is promoted to float before multiplication

// Example 3:
double result3 = y / z; // y is promoted to double before division

These rules ensure that there is no loss of precision during arithmetic operations and that the result is of the appropriate type.