Casting Primitive Data Types in Java

This tutorial guides you on casting primitive data types in order to convert from one primitive data type to another primitive data type in Java. This can be achieved in two ways, widening and narrowing. 

Casting Primitive Data Types – Widening

Primitive data types are classified in to two types, lower data types and higher data types. Note, the lower data types uses less memory and higher data types uses more memory. To know the lower and higher data types, the following representation might be useful for you.

byte,  short,  char,  int,  long,  float,  double
lower <-------------------------------------> higher

From the above representation, it is clear that char is lower data type compared to int data type. And float is higher data type compared to long. Note, boolean data type is not represented in the diagram, because it cannot be converted to any other data type.

Converting a lower data type to higher data type is known as “Widening”. The below examples are for casting primitive data types for the widening scenario.

Example 1:

char c = 'A';

int n = (int)c;  //n contains 65 which is the ASCII value of 'A'

Example 2:

int x = 2500;

float price = (float)x; // price contains 2500.0

Note, widening is safe to do because you won’t be facing any data loss or accuracy issues. That is the reason why even if programmer does not use casting operator, JVM compiler does the casting operation itself internally for you and hence this is also called as “Implicit Casting“.

Therefore, the following statements will work perfectly without using casting operator as shown in the example without any compilation issues.

1) char c = 'A';

   int n = c;  //n contains 65 which is the ASCII value of 'A'

2) int x = 2500;

   float price = x; // price contains 2500.0

Casting Primitive Data Types – Narrowing

You can convert from higher data type to lower data type and it is called as “Narrowing” or “Explicit Casting“. The below examples are for narrowing.

Example 1:

int n = 65;

char c = (char)n;  //c contains 'A'

Example 2:

double d = 22.467;

int n= (int)d; //nstores 22

From the above example, it is evident that when you convert higher data type (double) to lower data type (int), the value in “d” was “22.467” and when it is converted to int, the value has become “12” which is stored in “n“. Here we lost some digits.

Therefore, narrowing is not safe in case of primitive data types and hence Java compiler forces the programmer to use casting operator and the programmer must cast the data type. Since the casting is done by programmer explicitly, it is called as “Explicit Casting“.

For casting referenced data types or casting objects please refer Casting Object Data Types in Java.

Also See:


Notify of

Inline Feedbacks
View all comments