Type Casting in Java

As we learned data types, sometimes we may need to convert one data type to another. Simply, type casting means converting one data to another data type.


Types of Type Casting

In java, we have two types of type casting. They are:

  • Widening Casting or Implicit Casting
  • Narrowing Casting or Explicit Casting


Widening Casting or Implicit Casting

As you can see in above image, Widening casting is converting smaller data type to larger data type. It is done automatically easy to use.
Suppose we have int a = 5 and we want to convert a to double. So we can do so by, double b = a.
Take a look at this example:

public class LearnTypeCast { public static void main(String[] args) { int a = 9; double b = a; System.out.println(a); System.out.println(b); } }
It will simply give 5 and 5.0 as output.


Narrowing Casting or Explicit Casting

As you can see in above image, Widening casting is converting larger data type to smaller data type. It is done manually by placing the type in parentheses in front of the value.
Suppose we have double a = 5 and we want to convert a to int. So we can do so by, int b = (int) a.
Take a look at this example:

public class LearnTypeCast { public static void main(String[] args) { double x = 10.23; int y = (int) x; System.out.println(x); System.out.println(y); } }
It will simply give 10.23 and 10 as output.


Data Types in Java Previous Next String in Java