Type casting primitive data types in Java

This tutorial focuses on the different type-casting operations that could be performed in Java (such as double to int and vise verca), using primitive data-types, and the consequences from performing such operations.

What is Type Casting?

In programming, type casting is the process of “casting” a value of a certain data type, into a storage variable that was designed to store a different data type. Casting here mean the conversion of that value to another version that could fit the variable of the different data type. Type casting in certain cases could lead to loss of information, loss of precision and errors, if not performed carefully.

Type casting between whole numbers and floating points

To type cast a value into a certain variable, we use the assignment operator, and assign the variable with the value to be type-casted, preceded by
the type we are type casting into. i.e. :Datatype var = (Datatype) value ;

Lets visit the following example:

   public class TypeCasting1 {
        public static void main(String[]args){
            
            int x = 13;
            
            double y = (double)x; // here we type cast the value 13, to a double
            
            System.out.println("value of x : "+x); // 13
            System.out.println("value of y : "+y); // 13.0
        }
    }


The program above is an example of a type-casting operation. We first initialize an integer with the value of 13. Next, we type cast the value 13 into a double data type, and assign it to the variable y. The output of running the program is as follows:

value of x : 13
value of y : 13.0


Notice how the value 13 has a floating point, after being assigned to y. Please note that Java supports automatic type casting of integers to floating points since there is no loss of precision problems associated with it. On the other hand, Type casting floating points to integers is mandatory when assigning integer variables floating point values. Lets examine the next example:

public class TypeCasting2 {         
    public static void main(String[]args){
    double x = 13.4;                          //int y = x; // if we use this, a "loss of precision" error will occur             
    int y = (int)x; //type casting x to an int , type casting floating points to integers is necessary                         
    System.out.println("value of x : "+x); // 13.4             
    System.out.println("value of y : "+y); // 13.0         
}
}


In the example above, we type casted the floating point value “13.4” to an integer. Doing so will result in the deletion of the “.4”, in other words, this will cause the dismissal of the floating point. When assigning floating point values to integer variables, type casting is necessary. Failing to do so will result in the program not compiling with a “possible loss of precision error”. A loss of precision error is a warning to the programmer that loss of information could occur due to the programmer’s operation. Type casting is a way to enforce the programmer’s orders, where the programmer acknowledges the acceptance of the potential loss of information. Running the program will cause the following output:

value of x : 13.4
value of y : 13



Type casting integers to integers and floating points to floating points

Type casting is not just used to convert between floating points and integers, it is also used to convert between integers and floating points of different sizes. Take the following example:

public class TypeCasting3 {         
    public static void main(String[]args){                         
        short x = 129;             
        byte y = (byte)x; //need to type cast here. size of x = 16-bit > size of y = 8-bit                         
         System.out.println("value of x = "+x);             
         System.out.println("value of y = "+y);                      
         }     
     }


We initialize a short variable with a value of 129. The next statement, we assign y the value of x. But since x is a short, which is 16-bits of length,
and y is a byte, with 8 bits of length, there is a possible loss of information. Therefore, type casting is required by the Java compiler. We type cast x into a byte, assign it to y and print the values.
The following is the output of the above program.

value of x = 129
value of y = -127


Notice how the information got lost when we assigned the value of x to y. Remember when we said that the range of a byte variable is from -128 to 127. Since the value 129 is outside of that range, an error occurs, where y cannot store the value of x, hence, y is assigned a wrong value of -127 (due to bit overflow).

Summary

It is obvious now that type casting should be carefully used when applied to primitive data types. One should take provisions for all the possible values the variables could assume, and design their application accordingly, by using appropriate data types, and type casting only when necessary.

Type casting primitive data types in Java

Leave a Reply

Your email address will not be published. Required fields are marked *

Scroll to top