What is Java Typecasting?

Total Post:16

Points:112

 115  View(s)
Ratings:
Rate this:

Java Type Casting:-

Typecasting means that when we assign a one primitive data type to another data type.

There are two types of casting:-

  • Implicit Type Casting.
  • Explicit Type Casting.

Implicit Type Casting:-

  • When we convert smaller data type into a bigger data type.
  • It can be done automatically.
  • It is also known as “Widening Casting”.
  • byte -> short -> char -> int -> long -> float -> double.

Example

 class MyClass {

  public static void main(String[] args) {
    int myInt = 25;
    double myDouble = myInt; // Automatic casting: int to double

    System.out.println(myInt); // Outputs 25
    System.out.println(myDouble); // Outputs 25.0
  }
}

Explicit Type Casting:-

  • When we convert bigger data type into a smaller data type that type of casting is known as explicating typecasting.
  • It can be done manually. 
  • It is also known as “Narrowing Casting”.
  • double -> float -> long -> int -> char -> short -> byte.

Example

 class MyClass {
  public static void main(String[] args) {
    double myDouble = 22.71;
    int myInt = (int) myDouble; // Manual casting: double to int
    System.out.println(myDouble);   // Output: 22.71
    System.out.println(myInt);      // Outputs 22
  }
}


Answer

Please check, If you want to make this post sponsored

You are not a Sponsored Member. Click Here to Subscribe the Membership.