Type Conversion And Type Casting In Java

Type Conversion And Type Casting In Java
Type Conversion And Type Casting In Java

Introduction

A significant part of programming involves playing around with data. While performing some tasks, situations might arise where the data type has to be changed from one type to another. For example, while calculating the area of a circle using Pi, we get a decimal number, and that needs to be converted to integer if we desire to obtain the answer in integer format. 

Since Java is strongly typed, one often needs to convert from one data type to another. The programmer or the compiler can easily do this by using type casting and type conversion concepts.

In Java, there are thirteen types of type Conversions. You can explore more about them by referring to the Java Type Conversion section in the Official Oracle Java Documentation. This blog will dive deep into the concept of type conversion and type casting in Java in detail, along with some examples.

Before learning Type Conversion and Type Casting in Java, you should know about Java Data Types. So check out the blog on Java Data Types and Identifiers to get a better understanding.

Type Conversion

Type conversion is a process in which the data type is automatically converted into another data type. The compiler does this automatic conversion at compile time. The data type to which the conversion happens is called the destination data type, and the data type from which the conversion happens is called the source data type. If the source and destination data types are compatible, then automatic type conversion takes place.

For type conversion to take place, the destination data type must be larger than the source type. In short, the below flow chart has to be followed.

Flow chart for Type Conversion

This type of type conversion is also called Widening Type Conversion/ Implicit Conversion/ Casting Down.  In this case, as the lower data types with smaller sizes are converted into higher ones with a larger size, there is no chance of data loss. This makes it safe for usage.

In type conversion, the source data type with a smaller size is converted into the destination data type with a larger size.

Before looking at an example for the type conversion type, let’s see what happens when incompatible data types are given.

public class Main {
 public static void main(String[] args) {
   int intType = 20;
   // short is of lower data type than int
   short shortType = intType;
 
   System.out.println("intType: "+intType);
   System.out.println("shortType: "+shortType);
 }
}

Compile Time Error:

In the above case, short is of lower data type than int, hence a compile-time error occurs. In the next section, we will see how to solve this error.

Example for Type Conversion in Java:

public class Main {
 public static void main(String[] args) {
   int intType = 20;
   // float is of higher data type than int
   float floatType = intType;
 
   System.out.println("intType: "+intType);
   System.out.println("floatType: "+floatType);
 }
}

Output:

intType: 20
floatType: 20.0

Type Casting

It is a process in which the programmer manually converts one data type into another data type. For this the casting operator (), the parenthesis is used. Unlike type conversion, the source data type must be larger than the destination type in type casting. The below flow chart has to be followed for successful type casting.

Flow chart for Type Casting

Type casting is also called Narrowing Type Casting/ Explicit Conversion/ Casting Up. In this case, as the higher data types with a larger size are converted into lower ones with a smaller size, there is a chance of data loss. This is the reason that this type of conversion does not happen automatically.

In type casting, the source data type with a larger size is converted into the destination data type with a smaller size.

In one of the examples covered in type conversion, you might recollect we encountered an error while converting an int data type to short. Now, we will see how to solve that error by using type casting. 

Example for Type Casting in Java:

public class Main {
 public static void main(String[] args) {
  int intType = 20;
  // short is of lower data type than int
  short shortType = (short)intType;
  System.out.println("intType: "+intType);
  System.out.println("shortType: "+shortType);
 }
}

Output:

intType: 20
shortType: 20

Object Type Casting in Java

Till now, we saw how we could convert one data type to another. Now we will see the conversion between objects. Object type casting in Java is done by a process called Upcasting and Downcasting. Upcasting narrows down the list of methods and properties available to the object, and downcasting extends it.

Let’s explore more about them.

Upcasting in Java

The type casting in which the child class object is type casted to a parent class object is called Upcasting. The compiler implicitly performs this. This allows the child class object to access the variables and methods of the parent class.

Upcasting the object provides access to only parent class members and some child class members like the overridden methods.

Upcasting: child class object is type casted to a parent class object

The concept of Upcasting is closely related to inheritance. It basically casts a child class object to parent class object, upwards the inheritance tree. It is also called Generalisation/Widening

Let’s look at an example to understand upcasting.

// parent class
class Parent {
 String classType = "Parent";
 void display() {
   System.out.println(classType+" method.");
 }
 void displayParent() {
   System.out.println(classType+" method.");
 }
}
 
// child class
class Child extends Parent {
 String classType = "Child";
 void display() {
   System.out.println(classType+" method.");
 }
 void displayChild() {
   System.out.println(classType+" method.");
 }
}
 
public class Main {
public static void main(String[] args) {
  // child class object casted to parent class object
  Parent p = new Child(); 
  p.display();
  p.displayParent();
  p.displayChild();
 }
}

You will notice that a compile-time error is generated in the above program. This happens because the displayChild() method is not an overridden method in the child class; hence it is not accessible.

Check out the blog Understanding Method Overriding in Java to understand the concept better. Now let’s see how the above program works without calling the displayChild() method.

// parent class
class Parent {
 String classType = "Parent";
 void display() {
   System.out.println(classType+" method.");
 }
 void displayParent() {
   System.out.println(classType+" method.");
 }
}
 
// child class
class Child extends Parent {
 String classType = "Child";
 void display() {
   System.out.println(classType+" method.");
 }
 void displayChild() {
   System.out.println(classType+" method.");
 }
}
 
public class Main {
public static void main(String[] args) {
  // child class object casted to parent class object
  Parent p = new Child(); 
  p.display();
  p.displayParent();
}
}

Output:

Child method.
Parent method.

Downcasting in Java

The type casting in which the parent class object is typecasted to a child class object is called Downcasting. Downcasting does not show any compile-time error. However, the ClassCastException is thrown at runtime.  To avoid ClassCastException casting operator ( ) is used.

Downcasting: parent class object is typecasted to a child class object

Let’s look at an example to understand downcasting.

// parent class
class Parent {
 String classType = "Parent";
 void display() {
   System.out.println(classType+" method.");
 }
 void displayParent() {
  System.out.println(classType+" method.");
}
}
 
// child class
class Child extends Parent {
 String classType = "Child";
 void display() {
   System.out.println(classType+" method.");
 }
 void displayChild() {
  System.out.println(classType+" method.");
}
}
 
public class Main {
public static void main(String[] args) {
  // parent reference holds child object
  Parent p = new Child();
  // downcasting
  Child c = (Child)p; 
  
  c.display();
  c.displayParent();
  c.displayChild();
}
}

Output:

Child method.
Parent method.
Child method.

Note: In downcasting, the child class methods can also be accessed unlike upcasting.

Upcasting and Downcasting 

Important Points related to Type Conversion and Type Casting in Java

1. In Java, each byte, short, or char operand is automatically promoted to int while evaluated.

Example:

public class Main {
public static void main(String[] args) {
  int intType = 20;
  short shortType = 5;
  // final result obtained as integer
  int result = intType * shortType;
  System.out.println("result: "+result);
  System.out.println("result is of type: "+((Object)result).getClass().getSimpleName());
}
}

Note: To check the data type in Java, getClass().getSimpleName() method is used after type casting the primitive data type to Object.

Output:

result: 100
result is of type: Integer

2. If any one of the operands is of type long, float, or double, the whole expression is promoted to long, float, or double, respectively.

Example:

public class Main {
public static void main(String[] args) {
  int radius = 7;
  // final result stored as double
  double perimeter = 2 * Math.PI * radius;
  System.out.println("perimeter: "+perimeter);
  System.out.println("perimeter is of type: "+((Object)perimeter).getClass().getSimpleName());
}
}

Output:

perimeter: 43.982297150257104
perimeter is of type: Double

3. While evaluating expressions, the result is automatically updated to a larger data type of the operand. So the programmer has to typecast the result if it needs to be stored in any smaller data type.

Example:

public class Main {
public static void main(String[] args) {
  byte byteType = 10;
  // type cast to byte
  byteType = (byte) (byteType * byteType);
  System.out.println("byteType: "+byteType);
  System.out.println("byteType is of type: "+((Object)byteType).getClass().getSimpleName());
 }
}

Output:

byteType: 100
byteType is of type: Byte

Frequently Asked Questions

What is meant by type conversion and type casting in Java?

In type conversion, a compiler converts a lower data type into a higher data type. In typecasting, a higher data type is converted into a lower data type by the programmer.

What are the common methods used to change data types in Java?

Type Conversion and Type Casting in Java enable converting one data type into another.

What is explicit type conversion?

Explicit type conversion is when a higher data type is converted into a lower data type by the programmer explicitly.

What is automatic type conversion?

Automatic type conversion is when a compiler automatically converts a lower data type into a higher data type.

Differentiate between type conversion and type casting in Java based on data loss.

There is a chance of data loss in typecasting while the data is safe in type conversion.

Key Takeaways

That was all about Type Conversion and Type Casting in Java. This blog covered various concepts, examples, important points, and frequently asked questions relating to Type Conversion and Type Casting in Java were covered in detail. 

With the help of this blog, you are now in a position to solve some questions related to Type Conversion and Type Casting in Java on our CodeStudio Platform.

Don’t stop here. Check out our Java guided path to learn Java from Scratch. You can also check out the blog Difference between Type Casting and Type Conversion to understand Type Conversion and Type Casting in Java better.

We hope you found this blog useful. Feel free to let us know your thoughts in the comments section. 

By Hari Sapna Nair