Type casting in Java refers to converting one data type to another. This is commonly used when dealing with variables of different types in expressions. Java provides two types of casting: implicit casting (widening) and explicit casting (narrowing).
Why Use Type Casting?
// Implicit Casting (Widening) int intNum = 100; double doubleNum = intNum; // No need for explicit casting // Explicit Casting (Narrowing) double doubleVal = 9.78; int intVal = (int) doubleVal; // Explicitly casting double to int // Example of type casting with loss of data: System.out.println("Implicit Casting: " + doubleNum); // Output: 100.0 System.out.println("Explicit Casting: " + intVal); // Output: 9
int
to double
). No loss of data occurs here.(int)
), typically when a larger data type is assigned to a smaller one (like double
to int
). However, explicit casting may result in a loss of data, such as truncating decimal places.Tip: Always check the range of the target data type to avoid overflow or underflow issues when narrowing types.
When viewing code examples on mobile devices, ensure that the code blocks are scrollable horizontally. This prevents layout breaking on smaller screens.
Type casting is essential for handling different data types in Java. Understanding when and how to use both implicit and explicit casting ensures you can work with variables of various types without causing errors or data loss.
Practice Task: Create a Java program that uses both implicit and explicit casting. Try to handle a situation where explicit casting results in data loss.
Help others discover Technorank Learning by sharing your honest experience.
Your support inspires us to keep building!