Java — Type Casting
Widening (implicit)
int myInt = 9;
double myDouble = myInt; // Automatic casting: int to double
System.out.println(myDouble); // 9.0
Narrowing (explicit)
double myDouble = 9.78d;
int myInt = (int) myDouble; // Manual casting: double to int
System.out.println(myInt); // 9
Common conversions
// int to double
double d = 42;
// double to int
int i = (int) 3.99;
// int to String
String s = String.valueOf(42);
// String to int
int num = Integer.parseInt("42");
// String to double
double dbl = Double.parseDouble("3.14");
Mini Practice
- Convert int to double
- Convert double to int
- Convert number to String
- Parse String to number
Up Next
Continue with Math - Math operations.
Related Topics
Frequently Asked Questions about Type Casting
What is Type Casting in Java?
Type Casting is a fundamental concept in Java. This lesson explains it step by step with clear examples, making it easy for beginners to understand.
How do I learn Type Casting?
Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn Type Casting.
Why is Type Casting important in Java?
Type Casting is essential for Java development. Understanding this concept will help you write better code and solve real-world problems more effectively.