: 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:
- 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 todouble
. - If one of the operands is
float
, the other is converted tofloat
. - If one of the operands is
long
, the other is converted tolong
. - For all other cases, both operands are converted to
int
.
- Binary numeric promotion:
- If the operands are of different data types, binary numeric promotion applies.
- If one operand is
double
, the other is converted todouble
. - If one operand is
float
, the other is converted tofloat
. - If one operand is
long
, the other is converted tolong
. - If any of the operands is
int
, the other is converted toint
.
- Unary numeric promotion:
- If the operand is of type
byte
,short
, orchar
, it is promoted toint
before any other operation.
- If the operand is of type
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.