Java Type Promotion Rules

« Previous Tutorial Next Tutorial »

Java defines several type promotion rules that apply to the expressions.

They are as follows: First, all the byte, short, and char values are promoted to an int, as just described. Then, 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.

Java Type Promotion Example

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

/* Java Program Example - Java Type Promotion Rules */

public class JavaProgram
    public static void main(String args[])
        byte b = 42;
        char c = 'a';
        short s = 1024;
        int i = 50000;
        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);

When the above Java program is compile and executed, it will produce the following output:

java type promotion rules

Let's look closely at the type promotions that occur in this line from the above program:

double result = (f * b) + (i / c) - (d * s);

In the first subexpression, (f * b), b is promoted to a float and the result of the subexpression is float. Next, in the subexpression (i / c), c is promoted to int, and the result is of type int. Then, in (d * s), the value of s is promoted to double, and the type of the subexpression is double. Finally, these three intermediate values, float, int, and double, are considered. The outcome of float plus an int is a float. Then the resultant float minus the last double is promoted to double, which is the type for the final result of the expression.

« Previous Tutorial Next Tutorial »

Latest 5 Posts by CodesCracker


Quick Links
Signup - Login - Give Online Test