Type Conversion in Java – Explore Automatic & Explicit Type Casting

Free Java courses with 37 real-time projects - Learn Java

As you must already be familiar with, Java does have a lot of primitive data types. Which means there is often confusion on which datatype to use.

There is also the case where you have to change the datatypes on the fly to keep up with the dynamics of the program. Let us look at how we do that.

Type Conversion in Java

Yes, you guessed it right. Type Conversion is indeed the conversion of variables from one data type to another. In Java, there are two main types of type conversion.

  1. Explicit Type Conversion
  2. Implicit Type Conversion

Before we understand that we have to know the size hierarchy of data types.
Let us observe all of them in increasing order in the list below.

  • byte
  • short
  • int
  • long
  • float
  • double

Implicit Type Conversion

Java converts shorter data types to larger data types when they are assigned to the larger variable.

For example, if you assign a short value to an int variable then Java does the work for you and converts the short value to an int and stores it in the int variable.

This is similar to the fact that you can put a raisin in a XXL polythene bag. However, if you want to put the inverse you have to work out a solution because it is not going to be easy.

Let us look at examples now!

Java program to illustrate automatic type conversion.

package com.dataflair.typeconversion;
public class ImplicitConversion
{
    public static void main(String[] args) {
        
        int numberint;
        short numbershort;
        byte numberbyte;
        float numberfloat;
        double numberdouble;
        long numberlong;

        //We have the datatypes we need. Now let us set a value to the shortest datatype. 
        //That is byte. 

        numberbyte=21;
        numbershort=numberbyte;
        numberint=numbershort;
        numberlong=numberint;
        numberfloat=numberlong;
        numberdouble=numberfloat;

        System.out.println("The short value is "+numbershort);
        System.out.println("The byte value is "+numberbyte);

        System.out.println("The int value is "+numberint);

        System.out.println("The long value is "+numberlong);
        System.out.println("The float value is "+numberfloat);
        System.out.println("The long value is "+numberdouble);
        
        System.out.println("This is explicit conversion");
    }
}

Output:

The short value is 21
The byte value is 21
The int value is 21
The long value is 21
The float value is 21.0
The long value is 21.0
This is explicit conversion

Observe how the value in short automatically got converted to int without any explicit action by the programmer. This is automatic conversion. Java does this when you assign a lower size variable to a higher larger variable.

If you are having trouble learning about the different types of datatypes please read the “Datatypes in Java” article first.

Okay back to where we were. Now if you go ahead and try a different way of converting the data types, the compiler would not be happy. Don’t believe me? Let us try it out then.

Java program to discuss the problem with type conversion:

package com.dataflair.typeconversion;
public class ExplicitProblem {
    public static void main(String[] args) {
        
        int a=57;
        byte b =a;
        System.out.print(b);
        
    }
    
}

Output:

ExplicitProblem.java:5: error: incompatible types: possible lossy conversion from int to byte
byte b =a;

^

Explicit Type Conversion in Java

The conversion is lossy because the variable int is larger in size than the data type byte. That is why the compiler thinks it’s not safe to convert the entire data type because it would lose data.

Do not worry just yet, there is a beautiful work around for this problem and we are going to see that now.

Java program to illustrate the working of explicit conversion in Java

Whenever you want to explicitly convert the value of a certain data type to one lesser in size then you must use the name of the data type bound by round brackets in front of the variable name.

package com.dataflair.
public class ExplicitProblem {
    public static void main(String[] args) {
        
        int a=257;
        byte b =(byte)a;
        System.out.print(b);

    }
    
}

Output:

1

Hah! The output confused you? Well if it did not, your concepts are solid! For those who did not understand why this output changed and did not print 257, byte is actually capable of storing a max value of 255.

A single byte consists of 8 bits and it can store anything between -127 to 127. So the value is actually N mod 256. Here, in this case, 257 mod 256 equals 1 hence the output only shows 1.

This is the loss the compiler was talking about previously.

Choosing the correct data type is extremely important in programming and it comes with a lot of practice and knowledge.

Type Promotion in Expressions

This is a very interesting thing to ponder about. When there is an expression what happens to the datatypes? Do they all remain exactly as they were before or do they get promoted to other data types?

Well, in a particular expression Java promotes all the short, byte and the char characters to int datatype. However, if there are float, double data types present in the expression then all the values are promoted to the highest value datatype in the expression.

Confused? Don’t worry we have got you covered.

Java program to illustrate the promotion of type in expressions:

package com.dataflair.typeconversion;
public class TypePromotionExpression {
    public static void main(String[] args) {
        
        System.out.println("This program will illustrate the automatic type promotion of Java");


        int a=76;
        long l=65123l;
        float f = 70.26f;
        double d=98.9898d;
        char c='z';

        System.out.println(a+c/d-f+l);
    }
}

Output:

This program will illustrate the automatic type promotion of Java
65129.97244807581

Observe how the resultant data type is in double. This is automatic type promotion.

Explicit Type Casting in Expressions

Last but not least we have to understand that the automatic promotion may get us in trouble sometimes.

This is evident because as soon as you perform some operation on a shorter datatype, Java converts it to a larger data type.

What if we do not want the variable to change its type? For that we have to use explicit type conversion just like the one we learned in the previous topic.

After performing operations, we need to explicitly convert the resultant variable to the intended one if we want to preserve its type. How? Let us see.

Java program to illustrate the use of explicit type casting in expressions:

package com.dataflair.typeconversion;
public class TypePromotionExpression {
    public static void main(String[] args) {
        
        System.out.println("This program will illustrate the automatic type promotion of Java");


        byte a= 127;
        a++;
        System.out.println("Now the datatype of a has changed to int. a => "+a);
        a=(byte)a;//explicit conversion of int c to char c. 
        System.out.println("Now it’s back to a byte. a=> "+a);
        
    }
}

Output:

This program will illustrate the automatic type promotion of Java
Now the datatype of a has changed to int. a => -128
Now it’s back to a byte. a=> -128

Let us look at an example of character for a better understanding:

package com.dataflair.typeconversion;
public class TypePromotionExpression {
    public static void main(String[] args) {
        
        System.out.println("This program will illustrate the automatic type promotion of Java");


        char c='s';
        int a=1;
        int b=c+a;
        System.out.println("This means that b is now an int value "+b);
        System.out.println("We can explicitly typecast it to a character like this "+(char)(b));
        
        
    }
}

Output:

This program will illustrate the automatic type promotion of Java
This means that b is now an int value 116
We can explicitly typecast it to a character like this t

This is a classic example where you can see that the value gets converted from a character to an integer upon performing operations on it with an int value.

This is beautiful to observe.

Quiz on Type Conversion in Java

Summary

Phew! We are now at the end of another exciting article about type conversions in Java. One step closer to be a Java developer.

Now we know what ‘type conversion’ in Java is, how automatic and explicit type conversion work, how to avoid getting errors and how to explicitly convert any data type to a datatype of your choice, Efficient programs carefully use as much memory as they require.

Did you like this article? If Yes, please give DataFlair 5 Stars on Google

follow dataflair on YouTube

3 Responses

  1. Magesh says:

    I would like to add few points for short/Byte case.

    short num1 = 5;
    short num2 = 4;
    short result = num1 + num2; // compilation error. Because though num1 , num2 are short, when do arithmetic operation on these, it generate int result. so, here we are trying to assign a int value to short variable. So, it will through compilation error. So we need to do casting explicitly. i.e. short result = (short)(num1 + num2);

    same rule applies for byte type too.

  2. Jacob Snell says:

    On question 5, a String must always have Double quotes

Leave a Reply

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