Type Casting
In Java, type casting is the process of converting one data type into another.
In Java, there are two types of casting:
Widening Casting (automatically) — converting a smaller type to a larger type size, it is also called Implicit (Widening) Casting.byte -> short -> char -> int -> long -> float -> double
Implicit casting occurs when you assign a smaller data type to a larger data type. This type of casting is done automatically by the Java compiler and is also known as widening conversion. This is safe because there is no loss of information.
public class TypeCasting {
public static void main(String[] args) {
int myInt = 9;
double myDouble = myInt; // Automatic casting: int to double
System.out.println(myInt); // Outputs 9
System.out.println(myDouble); // Outputs 9.0
int num = 100;
long longNum = num; // implicit casting from int to long
float floatNum = longNum; // implicit casting from long to float
System.out.println(longNum); // Outputs 100
System.out.println(floatNum); // Outputs 100.0
}
}Narrowing Casting (manually) — converting a larger type to a smaller size type, it is also called Explicit (Narrowing) Casting.double -> float -> long -> int -> char -> short -> byte
Get AnjaliKesherwani’s stories in your inbox
Join Medium for free to get updates from this writer.
Explicit casting is required when you assign a larger data type to a smaller data type. This type of casting must be done manually by the programmer because there is a risk of data loss. It is also known as narrowing conversion.
public class TypeCasting {
public static void main(String[] args) {
//Narrowing Casting
double myDouble = 9.78d;
int myInt = (int) myDouble; // Manual casting: double to int
System.out.println(myDouble); // Outputs 9.78
System.out.println(myInt); // Outputs 9
double doubleNum = 100.04;
long longNum = (long) doubleNum; // explicit casting from double to long
int intNum = (int) longNum; // explicit casting from long to int
System.out.println(longNum); // Outputs 100
System.out.println(intNum); // Outputs 100
}
}Real-Life Example
Here’s a real-life example of type casting where we create a program to calculate the percentage of a user’s score in relation to the maximum score in a game. We use type casting to make sure that the result is a floating-point value, rather than an integer:
public class TypeCasting {
public static void main(String[] args) {
// Set the maximum possible score in the game to 500
int maxScore = 500;
// The actual score of the user
int userScore = 473;
/* 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;
// Print the result
System.out.println("maxScore is " + maxScore);
System.out.println("userScore is " + userScore);
System.out.println("User's percentage is " + percentage);
}
}Casting Between Reference Types
In addition to primitive data types, casting can also be applied to reference types (objects). When casting objects, it involves upcasting and downcasting within an inheritance hierarchy.
class Animal {
void makeSound() {
System.out.println("Animal sound");
}
}
class Dog extends Animal {
void makeSound() {
System.out.println("Woof");
}
void fetch() {
System.out.println("Dog fetches the ball");
}
}
public class TypeCasting {
public static void main(String[] args) {
Animal animal = new Dog(); // upcasting
animal.makeSound();
Dog dog = (Dog) animal; // downcasting
dog.fetch();
}
}Key Points
- Implicit Casting (Widening): Safe and automatic, from smaller to larger type.
- Explicit Casting (Narrowing): Manual and potentially unsafe, from larger to smaller type.
- Reference Type Casting: Requires upcasting and downcasting in an inheritance hierarchy.
Understanding type casting is essential for ensuring data integrity and avoiding runtime errors in Java programs.
Conclusion
In conclusion, type casting in Java is a fundamental concept that allows developers to convert one data type into another, Mastering type casting enables Java developers to manage data types efficiently and ensures that programs operate smoothly when handling different types of data. Proper use of casting is crucial in both primitive and reference type contexts to maintain data integrity and avoid common pitfalls.










