what is casting in java

what is casting in java

1 year ago 35
Nature

Type casting in Java is the process of converting a value of one data type to another data type, either manually or automatically. There are two types of type casting in Java:

  • Widening Type Casting: This is the process of converting a lower data type into a higher one, which is also known as implicit conversion or casting down. It is done automatically by the compiler and is safe because there is no chance of losing data. Widening type casting occurs when the target type is larger than the source type, and both data types are compatible with each other. For example, converting an int to a double is a widening type cast.

  • Narrowing Type Casting: This is the process of converting a higher data type into a lower one, which is also known as explicit conversion or casting up. It is done manually by the programmer using the parentheses. If we do not perform casting, then the compiler reports a compile-time error. In the case of narrowing type casting, the higher data types are converted into lower data types, and there is a loss of data. For example, converting a double to an int is a narrowing type cast.

In Java, there are 13 types of type conversion, but the major two types are widening and narrowing type casting. Widening type casting is done automatically, while narrowing type casting must be done manually by the programmer.

Read Entire Article