Logout

Casting

(Note to self - this could better be placed with the Types notes)

Occasionally we will want to convert variables between different types; most often this will be the case because we receive a variable as one type, but need to work with it as another type. We've already seen this by the use of Integer.parseInt() which converts a String to an int. But sometimes it's one numeric type to another numeric type which we want to convert.

Most important in dealing with numeric type conversions is "how big" each type is; i.e., how many bytes does each take up. For, a variable of a smaller type will fit nicely into a variable of a larger type. So an int (which takes up 32 bits) will fit nicely into the memory that has already been allocated for a double (64 bits).

Example of type conversion not requiring casting:

int i = 45;
long l = i;

This works fine - the smaller (a 32 bit int) being placed into the bigger (a 64 bit long).

But the reverse is not true; a bigger thing cannot fit into a smaller thing. So a double will not fit into an int (64 bits attempting to fit into 32 bits). But if we know that the particular variable value of the bigger type can be accommodated by the smaller type, then we can safely "cast" the bigger type to the smaller type. So for example, if we had the number 26.0 saved as a double, we know for sure that an int variable can hold it - in fact a signed int could be as small as around - 2 billion, and as big as around 2 billion. So certainly no problem with 26.0.

You cast by putting the type you want to cast to in parenthesis just before the variable of the larger type.

Example:

double d1 = 26.0;
int i1 = (int) d1;

So just be careful of trying to put too big a value into a certain type.

Example

double d1 = 6 000 000 000
int i1 = (int) d; //problem

This would cause a logical error one way or the other, and i would not store the value of 6 billion; it simply cannot since 6 billion is outside of the range that can be represented by a 32 bit int.