Type casting in Java is a process of assigning a value of one primitive data type to another. It is an essential concept in Java programming, enabling flexibility and precision in handling different data types. There are two main types of casting in Java: Widening Casting (automatic) and Narrowing Casting (manual).
Widening Casting
Widening casting happens automatically when converting a smaller data type to a larger one. This process is seamless and does not require explicit conversion by the programmer. The order of data types from smaller to larger is as follows:
byte -> short -> char -> int -> long -> float -> double
Example of Widening Casting
In this example, the integer smallNum
is automatically cast to a double largeNum
without any explicit conversion.
public class Main { public static void main(String[] args) { int smallNum = 9; double largeNum = smallNum; // Automatic casting: int to double System.out.println(smallNum); // Outputs 9 System.out.println(largeNum); // Outputs 9.0 } }
Narrowing Casting
Narrowing casting must be performed manually, as it involves converting a larger data type to a smaller one. This process requires the programmer to use explicit conversion by placing the target type in parentheses before the value.
double -> float -> long -> int -> char -> short -> byte
Example of Narrowing Casting
In this example, the double bigNum
is manually cast to an integer smallNum
using explicit conversion.
public class Main { public static void main(String[] args) { double bigNum = 9.78; int smallNum = (int) bigNum; // Manual casting: double to int System.out.println(bigNum); // Outputs 9.78 System.out.println(smallNum); // Outputs 9 } }
Real-Life Application of Type Casting
Type casting can be useful in various real-world scenarios. Consider a program that calculates the percentage of a user’s score in relation to the maximum score in a game. Type casting ensures the result is a floating-point number rather than an integer.
Example
In this example, the integer userPoints
is cast to a float before performing the division, ensuring an accurate floating-point result.
public class GameScore { public static void main(String[] args) { int maxPoints = 500; // Maximum possible score in the game int userPoints = 423; // User's actual score // Calculate the user's percentage score float percentageScore = (float) userPoints / maxPoints * 100; System.out.println("User's percentage score is " + percentageScore); } }