Java Typecasting with Types and Examples

Java Typecasting: In this tutorial, we will learn about typecasting (type conversion) in Java with its types and examples. By Preeti Jain Last updated : January 02, 2024

Java Typecasting (Type Conversion)

In Java programming, typecasting is also known as type conversion. The typecasting is the process in which a variable is converted from one data type to another.

Typecasting Types

Java supports two types of typecasting:

  1. Implicit Typecasting (Widening Conversion)
  2. Explicit Typecasting (Narrowing Conversion)

1. Java Implicit Typecasting (Widening Conversion)

The implicit type conversion converts a smaller-size datatype to a larger-size datatype. In this typecasting no data loss is there. The implicit type conversion is done by the compiler (i.e. automatic). It is not done by the user.

Hierarchy of implicit (widening) typecasting is: byte → short → char → int → long → float → double

Example of Implicit Typecasting (Widening Conversion)

public class Main {
  public static void main(String[] args) {
    int num1;
    byte num2 = 20;

    // We are assigning smaller datatype 
    // byte to larger datatype 
    num1 = num2;

    // Print the output 
    System.out.println("The value of num1 is : " + num1);
  }
}

Output

The value of num1 is : 20

2. Java Explicit Typecasting (Narrowing Conversion)

The explicit typecasting converts a larger-size datatype to a smaller-size datatype. In this typecasting data loss is there. The explicit typecasting is not done by the compiler (i.e., manually). It is done by the user.

Hierarchy of explicit (narrowing) typecasting is: double → float → long → int → char → short → byte

Example of Explicit Typecasting (Narrowing Conversion)

public class Main {
  public static void main(String[] args) {
    int num1;
    double num2 = 20.8;

    // We are assigning larger size datatype 
    // long to smaller size datatype 
    num1 = (int) num2;

    // Print the output 
    System.out.println("The value of num1 is : " + num1);
  }
}

Output

The value of num1 is : 20

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.