Type Casting in Java: Explanation & Practice
Convert between different data types
Problem summary
You receive a price as 29.99 (double) but need to display it as an integer (rounded down).
Starter code
public class Main {
public static void main(String[] args) {
double price = 29.99;
// Cast to int and print: Rounded price: $29
}
}Expected output and test cases
- Cast double to int
Rounded price: $29
Hints
- Use (int) before a double to cast it to integer
- Casting to int truncates (removes) the decimal part
- The syntax is: (targetType)value
Related Core Java Basics exercises
- Practice Declare Variables in Java
- Practice Swap Two Values in Java
- Practice Arithmetic Operations in Java
Practice all Core Java Basics exercises · Run this idea in the Java compiler