Type casting
- Java course
- Beginner
- Lesson 14/116
- 4 min
Learn type casting with (int), (double).
What is type casting?
Converting one type to another is called type casting. Java has two kinds: widening (automatic) and narrowing (explicit cast).
Widening happens automatically from a smaller to a larger type: int → long → double. No data is lost.
Narrowing needs an explicit cast like (int) from a larger to a smaller type. Data may be lost:
double d = 3.7;
int i = (int) d; // i = 3The fractional part is lost.
Practice Cast int and double
Write a Main class with a main method. Assign 9.99 to double price. Assign (int) price to int whole. Print whole with println.
Sample solution
public class Main {
public static void main(String[] args) {
double price = 9.99;
int whole = (int) price;
System.out.println(whole);
}
}Expected output
9
When do you need a cast?
A cast is needed when you convert a larger type to a smaller one. For example, to store a double result as an int you use (int).
Widening conversion is automatic: no cast is needed to turn an int into a double. The compiler does it for you.
Before casting, consider whether data may be lost. For example, going from long to int may overflow if the value exceeds the int range.
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Match the casting types
| Term | Meaning |
|---|---|
Widening |
Automatic |
Narrowing |
Explicit cast |
(int) |
Cast operator |
double→int |
Data loss |
2 What happens when you cast double 3.7 to int?
- Stays 3.7
- Becomes 4, rounded
- Becomes 3, fraction lost Correct answer
- Throws an error
Explanation: Narrowing cast drops the fraction, leaving 3.
3 Complete the cast operator
int x = ____ 3.7;
int x = (int) 3.7;
Explanation: The cast operator is (type) in parentheses.