Type Casting in Java

Introduction

Typecasting is a technique in which we convert one type of value into another. In this article, we will learn about typecasting in Java, its types, methods, and constructors provided in Java programming language. 

What is Typecasting in Java?

In Java, when you assign a value of one data type to another, the two types may not be compatible. If the data types are compatible, Java will perform the conversion automatically, known as automatic. Typecasting is also known as type conversion in Java. It's done fairly, but sometimes you may get errors. 

Typecasting is often necessary when a method returns data of type in a different form than we need to perform an operation.

Under the above certain circumstances, Typecasting can be carried out automatically. In other cases, it must be forced manually (Explicitly).

For example, assigning an int value to a long variable.

Syntax

dataType variableName = (dataType) variableToConvert;

Syntax of Type Casting in Java

The syntax for casting a type is to specify the target type in parentheses, followed by the variable's name or the value to be cast—for example, the following statement.

Syntax

int number;
float value = 32.33;
number= (int) value;

Types of Type Casting in Java

  1. Implicit Typecasting and Explicit Typecasting
  2. up-casting and down-casting
  3. Autoboxing and Unboxing

1) Implicit Typecasting and Explicit Typecasting
 

Implicit Typecasting in Java

Widening or Automatic Typecasting takes place when two data types are compatible with each other and converts automatically. Casting a type with a small range of a type with a larger range is known as widening Typecasting.

Typecasting from smaller type to larger type size,

byte -> short -> char -> int -> long -> float -> double

  • The two data types are compatible.
  • When we assign the value of a smaller data type to a bigger data type.
  • The destination type is bigger than the source type.

For Example, in Java, the numeric data types are compatible, but no automatic conversion is supported from numeric type to char or boolean. Also, char and boolean are not compatible with each other.

Implicit typecasting is also known as widening typecasting and automatic type conversion in Java.

The complete program of Widening Typecasting is listed below.

public class TypecastingExample3 {  
    public static void main(String[] args) {  
        int number = 10;  
        float point = number;  
        System.out.println(number);  
        System.out.println(point);  
    }  
}  

The above program generates the following output.

typecasting-exampe3-output

The numeric types, including integer and floating-point types, are compatible with each other.

Note. Although the automatic type conversions are helpful, they will not fulfill all needs. For example, what if you want to assign a float value to a byte variable? This conversion will not be performed automatically because a byte is smaller than a float. This kind of conversion is sometimes called a narrowing conversion since you are explicitly making the value narrower to fit into the target type.

float to int conversion in Java

The complete program for type conversion of float to int is listed below.

public class TypecastingExample1 {  
    public static void main(String[] args) {  
        int number;  
        float fval = 32.33f;  
        number = (int) fval;  
        System.out.println(number);  
    }  
}  

The above program generates the following output.

typecasting-example1-output

int to float conversion in Java

The int and float each take 4 bytes of memory. The int holds a whole number, and the float holds a floating-point number. Assignment of int to float is done automatically by JVM.

public class IntToFloatExample {  
    public static void main(String args[])  
    {  
        int i1 = 10;  
        float f1 = i1;  
        System.out.println("int value: " + i1);  
        System.out.println("Converted float value: " + f1);       
    }  
} 

The above program generates the following output.

int-to-float-example-output

double to int conversion in Java

The complete program for type conversion of double to int is listed below.

public class TypecastingExample2 {  
    public static void main(String[] args){  
        System.out.println((int)1.87);  
        System.out.println((double)1 / 2);  
    }  
}   

The above program generates the following output.

typecasting-example2-output

int to double conversion in Java

The complete program of int to double type conversion is listed below.

public class IntToDoubleExample {  
    public static void main(String args[]) {  
        int i = 200;  
        double d = i;  
        System.out.println(d);  
    }  
} 

The above program generates the following output.

int-to-double-example-output

double to byte conversion in Java

The complete program of double-to-byte type conversion is listed below.

public class DoubleTOByteExample {  
    public static void main(String args[])  
    {  
        double d1 = 10.5;  
        byte b1 = d1;  //compile time error
        byte b1 = (byte) d1;  //compile time error
        System.out.println("\ndouble value: " + d1);  
        System.out.println("Converted byte value: " + b1 );  
    }  
} 

The above program generates the following output.

double-to-byte-example-output

Note. When we try to type conversion of double to a byte in Java implicitly, it causes an error the byte data type takes 1 byte of memory, and double takes 8 bytes of memory. Assigning 8 bytes of memory to 1 byte of memory requires explicit casting.

byte to double conversion in Java

The complete program of byte-to-double type conversion is listed below.

public class ByteToDoubleExample {  
    public static void main(String args[]) {  
        byte b1 = 10;  
        double d1 = b1;  
        System.out.println("byte value: " + b1);  
        System.out.println("Converted double value: " + d1);  
    }  
} 

The above program generates the following output.

byte-to-double-example-output

The complete program of implicit typecasting is listed below, in which the casting performs automatically.

public class ImplicitConversionExample {  
    public static void main(String args[]) {  
        byte i = 50;  
        // No casting needed for below conversion  
        short j = i;  
        int k = j;  
        long l = k;  
        float m = l;  
        double n = m;  
  
        System.out.println("byte value : " + i);  
        System.out.println("short value : " + j);  
        System.out.println("int value : " + k);  
        System.out.println("long value : " + l);  
        System.out.println("float value : " + m);  
        System.out.println("double value : " + n);  
    }  
}  

The above program generates the following output.

implicit-typecasting-example 

Implicit Casting of a Class Type in Java

When we are assigning a smaller type to a larger type, there is no need for casting required. The same applies to the class type, as well. The complete program is listed below.

class Parent {  
    public void disp() {  
        System.out.println("Parent disp called");  
    }  
}  
public class ImplicitTypecastingExample2 extends Parent {  
//child class   
    public static void main(String args[]) {  
        Parent p = new ImplicitTypecastingExample2();  
        p.disp();  
    }  
} 

The above program generates the following output.

implicit-typecasting-example2

Explicit Typecasting in Java

When one type of data is assigned to a different kind of variable, a narrowing type conversion will take place if the following two conditions are met:

  • The destination type is smaller than the source type.
  • When these two conditions are met, a narrowing conversion takes place. For example, the int is insufficient to hold all valid double values, so the explicit cast statement is required.

Type casting from smaller type to larger type size:

byte -> short -> char -> int -> long -> float -> double

No automatic conversions from the numeric types to char or boolean. Also, char and boolean are not compatible with each other.

Explicit casting is also known as Narrowing casting.

The complete program of narrowing or Explicit Typecasting is listed below.

public class TypecastingExample4 {  
    public static void main(String[] args){  
        float point=10.5f;  
        int a=f;//Compile time error  
        int number=(int)point;  
        System.out.println(point);  
        System.out.println(point);  
    }  
}  

The above program generates a compile-time error.

typecasting-example4-output

The complete program of narrowing type casting is listed below.

public class TypecastingExample5 {  
    public static void main(String[] args){  
        float point=10.5f;  
        int number=(int)point;  
        System.out.println(point);  
        System.out.println(point);  
    }  
}  

The above program generates the following output.

typecasting-example5-output

Note. As you know, integers do not have fractional components. Thus, the fractional component is lost when a floating-point value is assigned to an integer type. When a floating-point value is assigned to an integer type: truncation takes place.

For example, if the value 45.12 is assigned to an integer, the resulting value will be 45. The 0.12 will have been truncated.

The complete program is listed below.

public class TypecastingExample6 {  
    public static void main(String[] args){ 
        int number=150;  
        byte b=(byte)number;  
        System.out.println(number);  
        System.out.println(b);  
    }  
}  

The above program generates the following output.

typecasting-example6-output

The complete program is listed below.

public class TypecastingExample7 {  
    public static void main(String[] args){  
        byte r=10;  
        byte s=10;  
        byte c=r+s;//Compile Time Error: because r+s=20 will be int  
        System.out.println(c);  
    }  
}  

The above program generates the compile time error.

typeCasting-example-output7

The complete program is listed below.

public class TypecastingExample8 {  
    public static void main(String[] args){  
        byte r=10;  
        byte s=10;  
        byte c=(byte)(r+s);  
        System.out.println(c);  
    }  
}  

The above program generates the following output.

typecasting-example8-output

double to byte conversion in Java

As we know, when we try to type the conversion of double to a byte in Java implicitly, it causes an error. The byte data type takes 1 byte of memory, and double takes 8 bytes of memory. Assigning 8 bytes of memory to 1 byte of memory requires explicit casting.

The complete program of double-to-byte conversion is listed below.

public class DoubleToByteExplicitConversion {  
    public static void main(String args[]) {  
        double d1 = 10.5;  
        byte b1 = (byte) d1;  
        System.out.println("\ndouble value: " + d1);  
        System.out.println("Converted byte value: " + b1);  
    }  
} 

The above program generates the following output.

doubletobyte-explicit-example-output

Explicit typecasting of a Class Type in Java

When assigning a larger type to a smaller one, we need to typecast it explicitly. The complete program is listed below.

class ParentClass {  
    public void disp() {  
        System.out.println("Parent disp called");  
    }  
}  
  
public class ExplicitExample extends Parent {  
    //child class  
    public void disp() {  
        System.out.println("Child disp called");  
    }  
  
    public static void main(String args[]) {  
        Parent p = new ExplicitExample();
        p.disp();  
        ExplicitExample c = p;  
        c.disp();  
    }  
} 

Note. When we run the above code, we will get an exception stating, "Type mismatch: cannot convert from Parent to Child".

explicit-example1-output

We need to cast it to the Child class to fix the code. The complete program is listed below.

class ParentClass {  
    public void disp() {  
        System.out.println("Parent disp called");  
    }  
}  
  
public class ExplicitExample extends Parent {  
    //child class  
    public void disp() {  
        System.out.println("Child disp called");  
    }  
  
    public static void main(String args[]) {  
        ExplicitExample p = new ExplicitExample();  
        p.disp();  
        ExplicitExample c = p;  
        c.disp();  
    }  
} 

The above program generates the following output.

explicit-example-output

2) up-casting and down-casting


Upcasting

Upcasting is casting a subtype to a supertype upward to the inheritance tree. Upcasting is not necessary. However, we need upcasting when we want to write general code that deals with only the supertype. The complete program of Upcasting is listed below.

class Super {  
    // super class  
    void Sample() {  
        System.out.println("method of super class");  
    }  
}  
public class TypecastingExample9 extends Super {  
    //sub class  
    void Sample() {  
        System.out.println("method of sub class");  
    }  
    public static void main(String args[]) {  
        Super obj = (Super) new TypecastingExample9();  
        obj.Sample();  
    }  
} 

The above program generates the following output.

typecasting-example9-output

Note. The actual object type does not change because of casting. The TypecastingExample9 object is still a TypecastingExample9 object. Only the reference type gets changed.

Down-casting

Downcasting is casting a subtype downward to the inheritance tree. Downcasting can fail if the actual object type is not the target object type. Downcasting is used more frequently than upcasting. We use downcasting when we want to access specific behaviors of a subtype. The complete program is listed below.

class Super1 {  
    void Sample() {  
        System.out.println("method of super class");  
    }  
}  
public class TypecastingExample10 extends Super1 {  
    void Sample() {  
        System.out.println("method of sub class");  
    }  
    public static void main(String args[]) {  
        Super1 obj = new TypecastingExample10();  
        TypecastingExample10 sub = (TypecastingExample10) obj;  
        sub.Sample();  
    }  
} 

The above program generates the following output.

typecasting-example10-output

Note. Here, in the teach() method, we check if there is an instance of a Dog object passed in, downcast it to the Dog type, and invoke its specific method, bark().

Autoboxing and Unboxing
 

Autoboxing

Autoboxing refers to automatically converting a primitive type variable to its corresponding wrapper class object. The compiler automatically handles the conversion when a primitive value is,

  • Passed as an argument to a function that is expecting a wrapper class object.
  • assigned to a variable of the type of wrapper class.

The complete program of autoboxing is listed below.

import java.util.ArrayList;  
import java.util.List;  
  
public class TypecastingExample11 {  
    public static void main(String[] args) {  
        List<Integer> list = new ArrayList<>();  
        for (int i = 0; i < 10; i++) {  
            //autoboxing by passing as an argument  
            //int values is converted to Integer  
            //by compiler during compilation  
            list.add(i);  
        }  
  
        System.out.println(list);  
        char c = 'a';  
        //autoboxing by assigning an char to Character object  
        Character ch = c;  
        System.out.println(ch);  
    }  
} 

The above program generates the following output.

typecasting-example11-output

Unboxing

Converting an object of a wrapper type to its corresponding primitive value is called unboxing. For example, conversion of Integer to int. The Java compiler applies unboxing when an object of a wrapper class is:

  • Passed as a parameter to a method that expects a value of the corresponding primitive type.
  • Assigned to a variable of the corresponding primitive type.

The complete program of unboxing is listed below.

public class TypecastingExample12 {  
    public static void main(String[] args) {  
        Integer integer = new Integer(-10);  
        int i = abs(integer);  
        System.out.println(i);  
  
        int j = integer;  
        System.out.println(j);  
    }  
  
    private static int abs(int i) {  
        return (i < 0) ? -i : i;  
    }  
} 

The above program generates the following output.

typecasting-example12-output

Summary

In this article, we learned about Type casting or conversion in Java and how to use type casting in Java programing language with examples. 


Similar Articles