Type Casting in Java

Typecasting is a basic concept of Java programming language. Assigning a value of one type to a variable of another type is known as Type Casting in Java.

Introduction

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

What is Typecasting in Java?

 
In Java, when you assign a value of one data type to another data type, the two types may not be compatible with each other.  If the data types are compatiable, then Java will perform the conversion automatically, known as automatic.  It's done fairly, but sometimes you may get errors.  Typecasting is also known as type conversion in Java. 
 
Typecasting is often necessary when a method returns a data of type in a different form, then 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 with each other, 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.
  1. public class TypecastingExample3 {  
  2.     public static void main(String[] args) {  
  3.         int number = 10;  
  4.         float point = number;  
  5.         System.out.println(number);  
  6.         System.out.println(point);  
  7.     }  
  8. }  
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, so that it will fit into the target type.
 

float to int conversion in Java

 
The complete program for type conversion of float to int is listed below. 
  1. public class TypecastingExample1 {  
  2.     public static void main(String[] args) {  
  3.         int number;  
  4.         float fval = 32.33f;  
  5.         number = (int) fval;  
  6.         System.out.println(number);  
  7.     }  
  8. }  
The above program generates the following output.
 
typecasting-example1-output 
 

int to float conversion in Java

 
The int and float, each takes 4 bytes of memory.  The int holds a whole number and float holds a floating-point number.  Assignment of int to float is done automatically by JVM.
  1. public class IntToFloatExample {  
  2.     public static void main(String args[])  
  3.     {  
  4.         int i1 = 10;  
  5.         float f1 = i1;  
  6.         System.out.println("int value: " + i1);  
  7.         System.out.println("Converted float value: " + f1);       
  8.     }  

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.
  1. public class TypecastingExample2 {  
  2.     public static void main(String[] args){  
  3.         System.out.println((int)1.87);  
  4.         System.out.println((double)1 / 2);  
  5.     }  
  6. }   
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.
  1. public class IntToDoubleExample {  
  2.     public static void main(String args[]) {  
  3.         int i = 200;  
  4.         double d = i;  
  5.         System.out.println(d);  
  6.     }  

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.
  1. public class DoubleTOByteExample {  
  2.     public static void main(String args[])  
  3.     {  
  4.         double d1 = 10.5;  
  5.         byte b1 = d1;  //compile time error
  6.         byte b1 = (byte) d1;  //compile time error
  7.         System.out.println("\ndouble value: " + d1);  
  8.         System.out.println("Converted byte value: " + b1 );  
  9.     }  

The above program generates the following output.
 
double-to-byte-example-output 
 
Note:
When we try to type conversion of double to 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.
  1. public class ByteToDoubleExample {  
  2.     public static void main(String args[]) {  
  3.         byte b1 = 10;  
  4.         double d1 = b1;  
  5.         System.out.println("byte value: " + b1);  
  6.         System.out.println("Converted double value: " + d1);  
  7.     }  

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.
  1. public class ImplicitConversionExample {  
  2.     public static void main(String args[]) {  
  3.         byte i = 50;  
  4.         // No casting needed for below conversion  
  5.         short j = i;  
  6.         int k = j;  
  7.         long l = k;  
  8.         float m = l;  
  9.         double n = m;  
  10.   
  11.         System.out.println("byte value : " + i);  
  12.         System.out.println("short value : " + j);  
  13.         System.out.println("int value : " + k);  
  14.         System.out.println("long value : " + l);  
  15.         System.out.println("float value : " + m);  
  16.         System.out.println("double value : " + n);  
  17.     }  
  18. }  
The above program generates the following output.
 
implicit-typecasting-example 
 

Implicit Casting of a Class Type in Java

 
When we are assigning smaller type to a larger type, there is no need for a casting required.  The same applies to the class type, as well.  The complete program is listed below.
  1. class Parent {  
  2.     public void disp() {  
  3.         System.out.println("Parent disp called");  
  4.     }  
  5. }  
  6. public class ImplicitTypecastingExample2 extends Parent {  
  7. //child class   
  8.     public static void main(String args[]) {  
  9.         Parent p = new ImplicitTypecastingExample2();  
  10.         p.disp();  
  11.     }  

The above program generates the following output.
 
implicit-typecasting-example2 
 

Explicit Typecasting in Java

 
When one type of data is assigned to another type 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 not large enough 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.
  1. public class TypecastingExample4 {  
  2.     public static void main(String[] args){  
  3.         float point=10.5f;  
  4.         int a=f;//Compile time error  
  5.         int number=(int)point;  
  6.         System.out.println(point);  
  7.         System.out.println(point);  
  8.     }  
  9. }  
The above program generates a compile time error.
 
typecasting-example4-output
 
The complete program of narrowing type casting is listed below.
  1. public class TypecastingExample5 {  
  2.     public static void main(String[] args){  
  3.         float point=10.5f;  
  4.         int number=(int)point;  
  5.         System.out.println(point);  
  6.         System.out.println(point);  
  7.     }  
  8. }  
The above program generates the following output.
 
typecasting-example5-output
 
Note: 
When a floating-point value is assigned to an integer type: truncation takes place.  As you know, integers do not have fractional components.  Thus, when a floating-point value is assigned to an integer type, the fractional component is lost. 
 
For example, if the value 45.12 is assigned to an integer, the resulting value will simply be 45. The 0.12 will have been truncated.
 
The complete program is listed below.
  1. public class TypecastingExample6 {  
  2.     public static void main(String[] args){ 
  3.         int number=150;  
  4.         byte b=(byte)number;  
  5.         System.out.println(number);  
  6.         System.out.println(b);  
  7.     }  
  8. }  
The above program generates the following output.
 
typecasting-example6-output
  
The complete program is listed below.
  1. public class TypecastingExample7 {  
  2.     public static void main(String[] args){  
  3.         byte r=10;  
  4.         byte s=10;  
  5.         byte c=r+s;//Compile Time Error: because r+s=20 will be int  
  6.         System.out.println(c);  
  7.     }  
  8. }  
The above program generates the compile time error.
 
typeCasting-example-output7
 
The complete program is listed below.
  1. public class TypecastingExample8 {  
  2.     public static void main(String[] args){  
  3.         byte r=10;  
  4.         byte s=10;  
  5.         byte c=(byte)(r+s);  
  6.         System.out.println(c);  
  7.     }  
  8. }  
The above program generates the following output.
 
typecasting-example8-output
 

double to byte conversion in Java

 
As we know, when we try to type a conversion of double to 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.
  1. public class DoubleToByteExplicitConversion {  
  2.     public static void main(String args[]) {  
  3.         double d1 = 10.5;  
  4.         byte b1 = (byte) d1;  
  5.         System.out.println("\ndouble value: " + d1);  
  6.         System.out.println("Converted byte value: " + b1);  
  7.     }  

The above program generates the following output.
 
doubletobyte-explicit-example-output 
 

Explicit typecasting of a Class Type in Java

 
When we are assigning larger type to a smaller type, we need to explicitly type cast it.  The complete program is listed below.
  1. class ParentClass {  
  2.     public void disp() {  
  3.         System.out.println("Parent disp called");  
  4.     }  
  5. }  
  6.   
  7. public class ExplicitExample extends Parent {  
  8.     //child class  
  9.     public void disp() {  
  10.         System.out.println("Child disp called");  
  11.     }  
  12.   
  13.     public static void main(String args[]) {  
  14.         Parent p = new ExplicitExample();
  15.         p.disp();  
  16.         ExplicitExample c = p;  
  17.         c.disp();  
  18.     }  

Note:
When we run the above code, we will be getting exception stating “Type mismatch: cannot convert from Parent to Child”
 
explicit-example1-output 
 
In order to fix the code, then we need to cast it to Child class.  The complete program is listed below.
  1. class ParentClass {  
  2.     public void disp() {  
  3.         System.out.println("Parent disp called");  
  4.     }  
  5. }  
  6.   
  7. public class ExplicitExample extends Parent {  
  8.     //child class  
  9.     public void disp() {  
  10.         System.out.println("Child disp called");  
  11.     }  
  12.   
  13.     public static void main(String args[]) {  
  14.         ExplicitExample p = new ExplicitExample();  
  15.         p.disp();  
  16.         ExplicitExample c = p;  
  17.         c.disp();  
  18.     }  

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.
  1. class Super {  
  2.     // super class  
  3.     void Sample() {  
  4.         System.out.println("method of super class");  
  5.     }  
  6. }  
  7. public class TypecastingExample9 extends Super {  
  8.     //sub class  
  9.     void Sample() {  
  10.         System.out.println("method of sub class");  
  11.     }  
  12.     public static void main(String args[]) {  
  13.         Super obj = (Super) new TypecastingExample9();  
  14.         obj.Sample();  
  15.     }  

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 to 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.  T he complete program is listed below.
  1. class Super1 {  
  2.     void Sample() {  
  3.         System.out.println("method of super class");  
  4.     }  
  5. }  
  6. public class TypecastingExample10 extends Super1 {  
  7.     void Sample() {  
  8.         System.out.println("method of sub class");  
  9.     }  
  10.     public static void main(String args[]) {  
  11.         Super1 obj = new TypecastingExample10();  
  12.         TypecastingExample10 sub = (TypecastingExample10) obj;  
  13.         sub.Sample();  
  14.     }  

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 the automatic conversion of 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.
  1. import java.util.ArrayList;  
  2. import java.util.List;  
  3.   
  4. public class TypecastingExample11 {  
  5.     public static void main(String[] args) {  
  6.         List<Integer> list = new ArrayList<>();  
  7.         for (int i = 0; i < 10; i++) {  
  8.             //autoboxing by passing as an argument  
  9.             //int values is converted to Integer  
  10.             //by compiler during compilation  
  11.             list.add(i);  
  12.         }  
  13.   
  14.         System.out.println(list);  
  15.         char c = 'a';  
  16.         //autoboxing by assigning an char to Character object  
  17.         Character ch = c;  
  18.         System.out.println(ch);  
  19.     }  

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.
  1. public class TypecastingExample12 {  
  2.     public static void main(String[] args) {  
  3.         Integer integer = new Integer(-10);  
  4.         int i = abs(integer);  
  5.         System.out.println(i);  
  6.   
  7.         int j = integer;  
  8.         System.out.println(j);  
  9.     }  
  10.   
  11.     private static int abs(int i) {  
  12.         return (i < 0) ? -i : i;  
  13.     }  

The above program generates the following output.
 
typecasting-example12-output 
 

Summary 

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