Type Casting in Java

In this article, we will learn about what is Type Casting in Java, along with examples and various types of Type Casting in Java. We will get to know about the widening and narrowing type casting in java and also about upcasting and downcasting. In the end, we will discuss the advantages and importance of Type Casting in Java.

Introduction to Type Casting in Java

The varied aspects of the Java programming language is effectively handled by a wide variety of data types. Unfortunately, we have to convert one data type into another one more frequently. The concept of Type Casting is used in this situation.

Java has a feature called type casting that allows the form or type of a variable or object to be cast into a different kind of object. The process of converting one data type to another is known as type casting. Let’s first discuss Java data types before moving on to typecasting.

Data Types in Java

Java is a statically-typed language which means that all the variables must be declared before using them. So, It is compulsory to declare the variable’s type, and also the names must be specified.
Data Types in Java are broadly divided into two major categories:

  • Primitive Data Types
  • Non-Primitive Data Types

Primitive Data Types in Java

Primitive Data Types are the most basic data types available in Java. There are 8 different primitive data types available in Java. These are
Boolean:
It stores only two types of Values which are true and false.

Example:

boolean flag = true;

Byte:
Byte Data Type is used to store values from -128 to 127. The default value of Byte is 0.

Example:

byte b = 67;

Char:
It is used to store Characters in Java.

Example:

char ch = 'a';

Int:
Integer data is a 32-bit Data Type used to store numbers. It is the default data type used for storing numbers until there is a big number that might overflow.

Example:

int num = 76768;

Short:
Short Data Type is half the size of the int Data Type. In java, it is of 16- bit.

Example:

short val = 67;

Long:
It is used for storing 64-bit data in memory.

Example:

long value = 895950;

Float:
A single-precision 32-bit IEEE 754 floating point is the float data type. It has an infinite value range. The default setting is 0.0F.

Example:

float decimal = 67.57f;

Double:
A double-precision 64-bit IEEE 754 floating point is the double data type. It has an infinite value range. Like float, the double data type is frequently used for decimal values. The default setting is 0.0d.

Example:

double d = 56564.7;

Non-Primitive Data Types in Java

Instances or objects are referred to as either non-primitive data types or reference data types. They are unable to directly store a variable’s value in memory. They save the variable’s memory address. Non-primitive data types are created by the user, in contrast to primitive data types, which are defined by Java. They were made by programmers, and null can be used to assign them. Non-primitive data types have equal sizes.

Various Non-Primitive Data Types available in Java are

  • Strings: String is defined as the sequence of characters.
  • Arrays: Array is defined as the collection of similar types of elements such as all int, or all long variables, etc.
  • Classes: A class is a user-defined data type that serves as the building block for objects. It includes methods and other declarations for the objects
  • Interfaces: Interfaces in Java are similar to Classes but it only contains abstract methods.
  • Enum: Enum is similar to Classes and Interfaces but it cannot be used to extend classes or for creating objects. Enums can implement interfaces.

Types of Typecasting in Java

Type Casting in Java is majorly divided into the following two categories i.e. Widening Type Casting in Java and Narrowing Type Casting. These are explained below in detail:

Widening Type Casting in Java with Primitive Data Types

Widening Typecasting is the process of converting a lower data type to a higher data type. This style of casting is also referred to as automated typecasting because Java automatically accomplishes it without any explicit code writing.

Two data types need to be compatible with one another to execute this conversion. In widening type casting, 19 different types of primitive conversion are possible:

  • Conversion of byte to short, byte to int, byte to long, byte to float, byte to double

    byte bi = 2;
    short s = bi;
    int i = bi;
    long 1 = bi;
    float f = bi;
    double d = bi;
  • Conversion of short to int, short to long, short to float, short to double

    short sh = 3;
    int i = sh;
    long 1 = sh;
    float f = sh;
    double d = sh;
  • Conversion of char to int, char to long, char to float, char to double

    char ch = 'g';
    int i = ch;
    long l = ch;
    float f = ch;
    double d = ch;
  • Conversion of int to long, int to float, int to double

    int val = 32 ;
    long l = val;
    float f = val;
    double d = val;
  • Conversion of long to float, long to double

    long val = 8878;
    float f = val;
    double d = val;
  • Conversion of float to double

    float dec = 23.45f ;
    double d = dec;

Code Implementation of Widening Type Casting in Java:

public class Main {
    public static void main(String[] args) {
        byte b = 5;
        short s = b;
        int i = s ;
        long l = s;
        float f = s;
        double d = s; 
        System.out.println("Examples of Widening Type casting...!!");
        System.out.println("byte to short : "+ s);
        System.out.println("byte to int : "+ i);
        System.out.println("byte to long : "+ l);
        System.out.println("byte to float : "+ f);
        System.out.println("byte to double : "+ d);
    }
}

Output:

Examples of Widening Type casting...!!
byte to short : 5
byte to int : 5
byte to long : 5
byte to float : 5.0
byte to double : 5.0

Widening Type Casting in Java with Objects (Upcasting)

Upacasting is a type of object typecasting which involves typecasting a child object to a parent class object. We may simply access the variables and methods of the parent class in the child class by utilizing upcasting. Here, we only access a portion of the procedure and variables. Only a few specific child class variables and methods are accessed.

Example:

class  Parent{  
   void PrintData() {  
      System.out.println("method of parent class");  
   }  
}  
  
class Child extends Parent {  
   void PrintData() {  
      System.out.println("method of child class");  
   }  
}  
class Main{  
   public static void main(String args[]) {  
      Parent obj1 = (Parent) new Child();  
      Parent obj2 = (Parent) new Child();   
      obj1.PrintData();  
      obj2.PrintData();  
   }  
}

Output:

method of child class
method of child class

Explanation: In the above example, we have defined a class Parent and a subclass Children which extends the Parent Class. Then we performed upcasting implicitly while defining the objects. Here the parent class is typecasted to the parent Class.

Narrowing Type Casting in Java with Primitive Data Types

Narrowing typecasting is the process of converting higher data types to lower data types. It is also known as explicit typecasting since Java does not perform it automatically; rather, the programmer must do it manually.

In narrowing type casting in java, there are 22 different primitive conversion types possible:

  • Conversion of short to byte, short to char

    short num = 65 ;
    byte b = (byte) num ;
    char c = (char) num ;
  • Conversion of char to byte, char to short

    char num = 65 ;
    byte b = (byte) num ;
    short s = (short) num ;
  • Conversion of int to byte, int to short, int to char

    int num = 12 ;
    byte b = (byte) num ;
    short s = (short) num ;
    char c = (char) num ;
  • Conversion of long to byte, long to short, long to char, long to int

    long num = 12 ;
    byte b = (byte) num ;
    short s = (short) num ;
    char c = (char) num ;
    int i = (int) num ;
  • Conversion of float to byte, float to short, float to char, float to int, float to long

    float num = 12.0f ;
    byte b = (byte) num ;
    short s = (short) num ;
    char c = (char) num ;
    int i = (int) num ;
  • Conversion of double to byte, double to short, double to char, double to int, double to long, double to float

    double num = 65.25 ;
    byte b = (byte) num ;
    short s = (short) num ;
    char c = (char) num ;
    int i = (int) num ;
    long l = (long) num ;
    float f = (float) num ;

Code Implementation of Narrowing Type Casting in Java:

public class Main {
    public static void main(String[] args) {
        float num = 65.0f;
        byte b = (byte) num;
        short sh = (short) num;
        char ch = (char) num;
        int i = (int) num;
        System.out.println("Examples of Narrowing primitive Type casting...!!");
        System.out.println("float to short : " + b);
        System.out.println("float to byte : " + sh);
        System.out.println("float to char : " + ch);
        System.out.println("float to int : " + i);

    }
}

Output:

Examples of Narrowing primitive Type casting...!!
float to short : 65
float to byte : 65
float to char : A
float to int : 65

Narrowing Type Casting in Java Objects (Downcasting)

When two classes hold the relationship of parent class and child class through inheritance, narrowing typecasting, which is similar to widening typecasting, can transform an object of one class into an object of another class. Inheriting classes are referred to as parent classes or superclasses, whereas classes that get inheritance are referred to as children classes or subclasses.

A parent class reference object is given to the child class during upcasting. Although it is not possible to give a parent class reference object to a child class in Java, if downcasting is used, there won’t be any compile-time errors. When we try to run the program, it throws “ClassCastException”. So Unlike narrowcasting requires the programmer to expressly use a cast operator.

Example:

 class Parent {   
    String name;   
      
    void showMessage(){   
        System.out.println("Parent method is called");   
    }   
}   
      
class Child extends Parent {   
    int age;   
     
    @Override  
    void showMessage()   {   
        System.out.println("Child method is called");   
    }   
}   
    
public class Main{  
    public static void main(String[] args){   
        Parent p = new Child();  
        p.name = "Shubham";  
          
        // Performing Downcasting Implicitly   
        //Child c = new Parent(); // it gives compile-time error   
          
        // Performing Downcasting Explicitly   
        Child c = (Child)p;   
    
        c.age = 18;   
        System.out.println(c.name);   
        System.out.println(c.age);   
        c.showMessage();   
    }   
}

Output:

Shubham
18
Child method is called

Explanation: In the above example, we have defined a class Parent and a subclass Children which extends the Parent Class. If we perform downcasting implicitly, it will throw compile time error. Then we performed downcasting explicitly.

Summary

  • The term "type casting" describes the transformation of one data type into another.
  • Widening type casting and Narrow type casting are the two major types of type casting.
  • Narrowing typecasting is the process of converting higher data types to lower data types. Since it needs to be done explicitly, it is also known as explicit type casting.
  • Widening typecasting is the process of converting lower data types to higher data types. Since the compiler may perform it implicitly, it is also known as Implicit TypeCasting.
  • On user-defined objects and classes, explicit downcasting and explicit upcasting are two types of explicit type casting that can be utilized.
  • Explicit upcasting refers to the assignment of a parent class reference to a child class object.
  • Explicit downcasting occurs when a parent class reference variable relating to an object in a child class is assigned to a child class reference variable.

Leave a Reply

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