03.06. Type Casting

Type Casting

  • Eclipse: Oxygen
  • Java: 1.8

In Java, Type Casting is a process of converting a variable of one data type into another.

Typecasting is of two types:

  • Implicit typecasting.
  • Explicit typecasting.

Implicit typecasting

 

Implicit type casting is also known as Widening or Automatic typecasting. When a small range data type variable is converted into a large range data type, The process is called implicit typecasting.

Example:

we initialize an int variable with a short value.

Output

Explicit typecasting

 

Explicit typecasting is also known as narrowing typecasting. When a large range data type is converted into small range data.

Example

We initialize the short variable y with int x, when we try to execute, the program will crash with “type mismatch” error. As we are trying to store large data type (int) into smaller data type variable (short).

Output

 

In this example, we initialize the short variable by assigning an integer variable, in the narrowing typecasting scenario; we have to explicitly typecast data.

Output

A yet another example of narrowing typecasting, double data is explicitly converted into float.

Output

Do you know?

  • Data type should be compatible for conversion. A non-primitive data type cannot be converted into a primitive type.
  • The precision loss may happen in Explicit typecasting.

Contributed by: Poonam Tomar

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments