next up previous
Next: The primitive data type Up: Unit 04 Previous: Assignments between different primitive

Explicit type conversion (casting)

If we want to compile and execute the wrong assignment statements in the previous table, we have to insert an explicit type conversion (also called type cast).


Cast

Syntax:
(type) expression

Semantics:

Converts the type of an expression to another type in such a way that operations involving incompatible types become possible.

Example:

int a = (int) 3.75;      // cast to int of the expression 3.75 (of type double)
System.out.println(a);   // prints 3

When we perform a cast, the result could be affected by a loss of precision: in the previous example, the value 3.75 is truncated to 3.


Example:

double d; float f; long l; int i; short s; byte b;

// The following assignments are correct
d = f;   f = l;   l = i;   i = s;   s = b;

// The following assignments are NOT correct
f = d;   l = f;   i = l;   s = i;   b = s;

// The following assignments are correct,
// but the result could be affected by a loss of precision
f = (float)d;   l = (long)f;   i = (int)l;   s = (short)i;   b = (byte)s;


next up previous
Next: The primitive data type Up: Unit 04 Previous: Assignments between different primitive