Java type promotion rules

Introduction

Java defines several type promotion rules:

  • all byte, short, and char values are promoted to int
  • if one operand is a long, the whole expression is promoted to long.
  • If one operand is a float, the entire expression is promoted to float.
  • If any of the operands are double, the result is double.

The following code shows how each value in the expression gets promoted to match the second argument to each binary operator:


public class Main {
  public static void main(String args[]) {
    byte b = 50;// w  ww.  j a  v a2s  .  c o  m
    char c = 'a';
    short s = 1234;
    int i = 99999;
    float f = 5.67f;
    double d = .1234;
    double result = (f * b) + (i / c) - (d * s);
    System.out.println((f * b) + " + " + (i / c) + " - " + (d * s));
    System.out.println("result = " + result);
  }
}

Promotions allowed for primitive types.

Type Valid promotions
doubleNone
float double
long float or double
int long, float or double
char int, long, float or double
short int, long, float or double (but not char)
byte short, int, long, float or double (but not char)
boolean None (boolean values are not considered to be numbers in Java)



PreviousNext

Related