Type casting in Java occurs when you assign a value from one primitive data type to another.
In Java, casting can be categorized into two types:
Widening Casting(automatically) – Expanding the size of a type.
byte
-> short
-> char
-> int
-> long
-> float
-> double
Narrowing Casting (manually) – Reducing the size of a type.
double
-> float
-> long
-> int
-> char
-> short
-> byte
Automatic widening casting occurs when passing a smaller-sized type to a larger-sized type.
public class Main {
|
Manual narrowing casting is performed by enclosing the type in parentheses ( ) before the value.
public class Main { |
Below is an example demonstrating type casting in action, where we develop a program to determine the percentage of a user’s score relative to the maximum score achievable in a game.
We utilize type casting to ensure that the outcome is a floating-point value, as opposed to an integer.
// Set the maximum possible score in the game to 500 int maxScore = 500; // The actual score of the user int userScore = 423; /* Calculate the percantage of the user’s score in relation to the maximum available score. Convert userScore to float to make sure that the division is accurate */ float percentage = (float) userScore / maxScore * 100.0f; System.out.println(“User’s percentage is “ + percentage); |