Java Tutorial-Java Type Casting

Java Type Casting

Type Casting can be done with primitive data types when you assign a one type to another. The two types of type casting are:

  • Widening Casting (automatic) – converting smaller type to a larger type

            byte -> short -> char -> int -> long -> float -> double

  • Narrowing Casting (manual) – converting larger type to smaller type

            double -> float -> long -> int -> char -> short -> byte


Widening Casting – Example

int xInt = 10;
double xDouble = xInt;
             
System.out.println(xInt);
System.out.println(xDouble);

Output:

10
10.0

Narrowing Casting – Example

double xDouble = 13.90;
int xInt = (int) xDouble;
             
System.out.println(xDouble);
System.out.println(xInt);

Output:

13.9
13