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 type casting. When small range data type variable is converted into large range data type, The process is called implicit type casting.

Example:

we initialize an int variable with a short value.

Output

10

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

Exception in thread “main” java.lang.Error: Unresolved compilation problem:

            Type mismatch: cannot convert from int to short 

            at challanges.Hello.main(Hello.java:7)

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

Output

10

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

Output

10.012345

Do you know?

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

Contributed by: Poonam Tomar


VIEW COURSES

Buy me a coffee!

 

PayTM QR (INDIA)

  • Get video tutorials
  • Project files set
  • Get Certified

Leave a Reply

avatar
  Subscribe  
Notify of
Close Menu