Java Type Casting: Widening and Narrowing

Understand the two types of type casting in Java: widening casting (automatic) and narrowing casting (manual). Learn how to convert primitive data types from one to another with ease and avoid common pitfalls.



Java Type Casting

Type casting in Java involves converting a value of one primitive data type to another type. There are two types of casting:

  • Widening Casting (Automatic): Converts a smaller type to a larger type size.
  • Narrowing Casting (Manual): Converts a larger type to a smaller type size.

Widening Casting

Widening casting is done automatically when passing a smaller size type to a larger size type:

Syntax

int myInt = 9;
double myDouble = myInt; // Automatic casting: int to double
    
Output

9
9.0
    

Narrowing Casting

Narrowing casting must be done manually by placing the type in parentheses () in front of the value:

Syntax

double myDouble = 9.78d;
int myInt = (int) myDouble; // Manual casting: double to int
    
Output

9.78
9
    

Real-Life Example

Here's a real-life example of type casting to calculate the percentage of a user's score in a game:

Syntax

// Set the maximum possible score in the game to 500
int maxScore = 500;

// The actual score of the user
int userScore = 423;

/* Calculate the percentage of the user's score in relation to the maximum available score.
Convert userScore to float to ensure accurate division */
float percentage = (float) userScore / maxScore * 100.0f;

System.out.println("User's percentage is " + percentage);