Module 2: Output, Input, Variables, and Types
Type Conversion and Casting
Convert between common types and understand when Java does it automatically versus when you must cast explicitly.
Author
Java Learner Editorial Team
Reviewer
Technical review by Java Learner
Last reviewed
2026-04-16
Java version
Java 25 LTS
Learning goals
- Recognize simple automatic widening conversions
- Use an explicit cast for narrowing conversions
- Avoid accidental data loss in beginner code
Automatic widening: Java can safely move from a smaller numeric type to a larger one, such as from int to double.
Explicit casting: When you go from a larger type to a smaller one, you must cast. For example, (int) 9.8 becomes 9.
String conversion is different: Numbers do not automatically turn into numbers from text input. You often need methods such as Integer.parseInt(...) later when converting strings.
Why this matters: Conversions show up quickly when you read input, do math, or format output for the user.
Runnable examples
Automatic conversion from `int` to `double`
public class Main {
public static void main(String[] args) {
int whole = 7;
double decimal = whole;
System.out.println(decimal);
}
}Expected output
7.0
Explicit cast from `double` to `int`
public class Main {
public static void main(String[] args) {
double price = 19.99;
int roundedDown = (int) price;
System.out.println(roundedDown);
}
}Expected output
19
Common mistakes
Assuming a cast rounds a decimal normally
A simple cast to `int` truncates the decimal part instead of rounding.
Mini exercise
Create a `double` value, cast it to `int`, and print both values.
Summary
- Some conversions are automatic, but narrowing conversions need a cast.
- Casting can lose information.
- Type conversion becomes important as soon as programs handle real input.
Next step
Module 3 builds on these basics with operators, expressions, and strings.
Sources used