Software Development

Java Numeric Promotion Rules

Java Primitive Types

Consider the following Java primitive types and take note of the type’s size, e.g., 8-bit. For this post, we can ignore boolean, and char as they are not numeric types.

[wp_ad_camp_1]

KeywordTypeExample
booleantrue or falsetrue
byte8-bit integral value123
short16-bit integral value123
int32-bit integral value32-bit integral value
long64-bit integral value123
float32-bit floating-point value123.45f
double64-bit floating-point value123.456
char16-bit Unicode value'a'

Given the following table of Java primitive types, Java follows when applying operators to data types.

  1. If two values have different data types, Java will automatically promote one of the values
    to the larger of the two data types.
  2. If one of the values is integral and the other is floating-point, Java will automatically
    promote the integral value to the floating-point value’s data type.
  3. Smaller data types, namely byte, short, and char, are first promoted to int any time
    they’re used with a Java binary arithmetic operator, even if neither of the operands is
    int.
  4. After all promotion has occurred and the operands have the same data type, the resulting
    value will have the same data type as its promoted operands.

Rule 1 Examples:

[wp_ad_camp_2]

Rule 2 Examples:

Rule 3 Examples:

Rule 4 Examples:

Rule 4 simple means the result of an arithmetic operation will have the same type as the type all operands promoted to. It is based on the first three rules.

[wp_ad_camp_3]

Loading

Got comments or suggestions? We disabled the comments on this site to fight off spammers, but you can still contact us via our Facebook page!.


You Might Also Like