Java: Type Casting

A few times, in Java, there may be a need to convert one data type to another. For instance, from a double to an int. This process is known as type casting.

In case a smaller data type has to be converted to a bigger data type, coders need not do much explicitly. For example, a short (2 bytes) variable is assigned to a double (8 bytes) below, in a process referred to as a widening primitive conversion, and the programmer need not use any special code for that.  

short userAge = 30;
double myDouble = userAge;

To convert a larger data type to a smaller one, parenthesis must be used to indicate it explicitly. This method is called a narrowing primitive conversion and can be understood by looking at the example below.

int x = (int) 30.7;

In this case, a double (8 bytes) can be cast into an int (4 bytes).

It is best to avoid narrowing conversion, as it is a risky business. That is because one can easily lose data using this type of conversion. For instance, casting a double value of 30.7 to an int gives 30 as the answer and not 31. As one might guess, the decimal part becomes truncated in this method.   

A double variable can be cast into a float. As discussed in a previous lesson, Java tends to take all non-integer numbers as a double, and the only way to turn them into float is by integrating the suffix “F” at the end of a number. Another method of doing this is:    

float age2 = (float) 30.7;

Now, the value of age2 will be 30.7.

Casting is not relevant just for numeric types. However, this lesson will not explore other types of casting due to it being beyond a beginner programmer’s scope.

Leave a Reply

%d bloggers like this: