Member-only story
Casting is an essential concept in Java that allows developers to convert one type of data into another. This operation is particularly useful when working with variables of different data types and is a fundamental feature of Java’s type system. In this blog, we will delve into the concept of casting, its types, and practical use cases.
What is Casting?
Casting in Java is the process of converting a variable from one data type to another. It can be broadly categorized into two types:
- Implicit Casting (Widening Conversion)
- Explicit Casting (Narrowing Conversion)
1. Implicit Casting (Widening Conversion)
Implicit casting happens automatically when a smaller data type is assigned to a larger data type. This type of casting does not require any explicit syntax because there is no loss of information.
Example:
public class ImplicitCasting {
public static void main(String[] args) {
int intValue = 42;
double doubleValue = intValue; // Implicit casting
System.out.println("Integer Value: " + intValue);
System.out.println("Double Value: " + doubleValue);
}
}
Output:
Integer Value: 42
Double Value: 42.0