Java Casting: Converting Data Types
Java is a strongly-typed language, which means you can't always assign values of one type to another directly. Casting helps you convert one data type into another.
Types of Casting in Java
There are two main types of casting:
- Widening Casting (Automatic Conversion)
- Also known as upcasting
- Java automatically converts a smaller type to a larger type
- Safe, as there's no data loss
Example:
public class WideningExample {
public static void main(String[] args) {
int num = 100;
double d = num; // automatic casting (int → double)
System.out.println("Integer value: " + num);
System.out.println("Double value: " + d);
}
}
Output:
Integer value: 100
Double value: 100.0
- Narrowing Casting (Manual Conversion)
- Also known as downcasting
- You need to manually tell Java to convert a larger type to a smaller type
- Risky, as data may be lost
Example:
public class NarrowingExample {
public static void main(String[] args) {
double d = 99.99;
int num = (int) d; // manual casting (double → int)
System.out.println("Double value: " + d);
System.out.println("Integer value: " + num);
}
}
Output:
Double value: 99.99
Integer value: 99
By understanding widening and narrowing casting, you can effectively work with different data types in Java.
Top comments (0)