Type Casting

Type Casting

In Java, type casting is a method or process that converts a data type into another data type in both ways manually and automatically. The automatic conversion is done by the compiler and manual conversion performed by the programmer.

Types of Type Casting

There are two types of type casting:

  • Widening Type Casting
  • Narrowing Type Casting

Widening Type Casting

Converting a lower data type into a higher one is called widening type casting. It is also known as implicit conversion or down casting . It is done automatically. It is safe because there is no chance to lose data. It takes place when:

  • Both data types must be compatible with each other.
  • The target type must be larger than the source type.
  1. byte -> short -> char -> int -> long -> float -> double

Narrowing Type Casting

Converting a higher data type into a lower one is called narrowing type casting. It is also known as explicit conversion or up casting . It is done manually by the programmer. Narrowing casting must be done manually by placing the type in parentheses in front of the value . If we do not perform casting then the compiler reports a compile-time error.

  1. double -> float -> long -> int -> char -> short -> byte  


Post a Comment

0 Comments