Java Type Casting

3 min read ·

Type casting means converting one data type into another data type.
In Java, sometimes we need to convert one variable type into another type to perform operations correctly.
Example Converting int to double Converting double to int
Java supports two types of casting
  1. Implicit Casting
  2. Explicit Casting

1. Implicit Casting

Also called Widening Casting.
It happens automatically when converting a smaller data type into a larger data type.
Order of widening
byte → short → int → long → float → double

Example of Implicit Casting

Output Integer value: 10 Converted to double: 10.0
Java automatically converts int into double because double can store larger values.
Note

Widening casting is safe because no data is lost.


2. Explicit Casting

Also called Narrowing Casting.
It happens manually when converting a larger data type into a smaller data type.
We must use parentheses with the target data type.

Example of Explicit Casting

Output Double value: 9.78 Converted to int: 9
Decimal part is removed after casting.
Caution

Narrowing casting may cause data loss because the smaller type cannot store all information.


Type Casting Between Primitive Types

Example 1

Example 2


Real World Example

Suppose a user enters marks as double because marks may contain decimal values.
But the school system stores marks as int.
Real World Scenario

Banking systems often convert numeric types while calculating interest and storing final values.


Type Casting with Division

Very common mistake happens during division.
Output 2.5
If you do not cast, result will be 2 because integer division removes decimal part.

Casting Between char and int

Java allows conversion between char and int.

Example

Output Character: A ASCII Value: 65 Converted Character: B
Pro Tip

When working with characters and numbers, remember that Java internally uses ASCII values.


Exercise

  1. Create a program that converts double value 45.89 into int and print both values.
  2. Create a program that divides two integers and prints decimal result using casting.
  3. Convert int value 90 into char and print the character.