Primitive Type Conversions

Sometimes you can assign a value of one type to a variable of another type.  If the types are compatible, Java does the conversion automatically.  For example,

int x = 10;
long y = x;

But there are not automatic conversions for all type combinations.  For example, there is no automatic conversion from double to byte or from character to boolean.

An automatic type conversion will take place if

  • The two types are compatible
  • The destination type is larger than the source type

Type Promotion

Some expressions automatically promote values to another type.  Here are the rules.

  • All byte, short and char values are promoted to int when evaluating an expression.
  • If one operand is a long, the entire expression is promoted to a long.
  • If one operand is a float, the entire expression is promoted to a float.
  • If one operand is a double, the entire expression is promoted to a double.
byte a;
. . .
a = a * 2;              // wrong - a is promoted to an int
a = (byte) (a * 2);     // ok

Casting

To perform a conversion between incompatible types or from a larger type to a smaller type you must cast one to the other using the following form: (target_type) value.  This is called narrowing.

int a;
byte b;
. . .
b = (byte) a;

When a floating-point number is cast to an integer, the fractional part is lost.  This is called truncation.

int a;
double b;
. . .
a = (int) b;

© 2017, Eric. All rights reserved.