forum

Home / DeveloperSection / Forums / What is Java Typecasting?

What is Java Typecasting?

Nitin Kushwaha 500 10-Jul-2019

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
  }
}



Updated on 10-Jul-2019

Can you answer this question?


Answer

0 Answers

Liked By