Casting, Promotion and Casting of Expressions


Casting means assigning a value of one type to a variable of another type. If the two types are compatible, the Java software performs the conversion automatically. For example, an int value can always be assigned to a long variable.

Where information might be lost in an assignment, the compiler requires that you confirm the assignment with a cast. For example, squeeze a long value into an int variable like this:

long bigValue = 99L;

int squashed = bigValue; // Wrong, needs a cast

int squashed = (int) bigValue; // OK

int squashed = 99L; // Wrong, needs a cast

int squashed = (int) 99L; // OK, but…

int squashed = 99; // default integer literal

The desired target type is placed in parentheses and used as a prefix to the expression that must be modified. Although it might not be necessary, it is advisable to enclose the entire expression to be cast in parentheses. Otherwise, the precedence of the cast operation can cause problems.


Variables can be promoted automatically to a longer form (such as int to long) when there would be no loss of information.

long bigval = 6; // 6 is an int type, OK

int smallval = 99L; // 99L is a long, illegal

double z = 12.414F; // 12.414F is float, OK

float z1 = 12.414; // 12.414 is double, illegal

In general, you can think of an expression as being assignment-compatible if the variable type is at least as large (maximum value) as the expression type.

For binary operators, such as the + operator, when the two operands are of primitive numeric types, the result type is determined as the largest type of either operand, or int. Therefore, all binary operations on numeric types result in at least an int result, and possibly a larger one if long, float, or double operands are in the expression. This might result in overflow or loss of precision when the result is assigned to a variable.

For example, the following code fragment:

short a, b, c;

a = 1;

b = 2;

c = a + b;

causes an error because it raises each short to an int before operating on it. However, if c is declared as an int, or a cast is done as:

c = (short)(a + b);

then the code works.