Sometimes it is necessary to convert a value from one type to a closely related type, eg from int
to long
. That particular conversion is very easy and always permitted because the range of values for long
encompasses the entire range for int
. So we can write
int i = 32000; long l = i;
But the opposite will be rejected by the compiler, even if the actual value used is OK:
long l = 32000; int i = l; // FAILS TO COMPILE
If we know that the values will in fact always be within range, or even if we don't, we can force the compiler to accept it with a "cast" which consists of putting the target type in parentheses:
long l = 32000; int i = (int) l; // ACCEPTED
Here are some further examples. Read this as one continuous program:
short sx = 10, sy = 1000; // Used in all the following
int ix = (int) sx; // Safe enough. (int) is the cast
float fx = (float) sx; // Similar - quite safe.
byte b1 = sy; // Compiler rejects as error.
byte b2 = (byte) sy; // Compiler allows but
// what does this do?
int iy = sy; // Compiler allows - cast is
// optional, there's no risk.
float fy = sy; // Ditto
int iy2 = (int) fy; // Allowed, but next line...
int iy3 = Math.round (fy);
// ... is likely to be better. Why?
boolean bb = true;
int ib = (int) bb; // No way! Not a related type.
This is allowed, and it is the way to get the character code:
char ch = 'A';
int code = (int) ch;
All examples above were casting between base (primitive) types. Later we will often cast between related class types. The same kind of syntax will be used:
String s = (String) object;
Customer cust1 = (Customer) person;