Two types of Type Casting

Type Casting in Java

We know data types in Java, if we want to convert one type into another data type, we can achieve it by using type casting in java.

Type Casting in Java:

Typecasting is when we convert one type into another data type manually or automatically. Automatic typecasting is done internally by a compiler. Manual type casting is done by the programmer.

There are two types of typecasting
1.Implicit Type Casting
2.Explicit Type Casting


Section 1: Implicit TypeCasting

This is also known as Widening casting or Upcasting. It is automatically done by the compiler when converting lower type data into higher type. Example converting float into double.

For implicit casting, need to check if they are compatible with each other. Such number types can be converted into another number type, not a string or boolean type.

Implicit type casting follows the following order:

Type Casting in Java

Note for implicit casting:
1.Both the types should be compatible with each other
2.The type in which data is converted must be larger than the source type.

Example :

Type Casting in Java

In the above example, we are converting int type into long and float. Since we are upcasting the types a compiler will allow it and automatically casts the value from int to long o float.

If we try to cast int as byte then compile will not allow it and will give compile-time error as shown in the below example:

Type Casting in Java

-A blog by Shwetali Khambe

Related Posts