Going from a smaller type to a bigger one, like int to double, is safe, so Java does it automatically. This is called widening. Going from bigger to smaller, like double to int, can lose information. So Java makes you ask for it, with a cast. This is narrowing.
An int goes into a double automatically. To go back, we write the type in brackets, before the value. Casting doesn't round. It just cuts off the decimals. Casting one side to double fixes whole number division. And Math dot round rounds properly. Run it. Seven becomes seven point zero. Nine point nine nine becomes nine. Seven over two is three, or three point five with a cast. And rounding gives ten.
Main.javajava
public class Main { public static void main(String[] args) { int cups = 7; double exact = cups; System.out.println("Widened: " + exact); double price = 9.99; int pounds = (int) price; System.out.println("Narrowed: " + pounds); int a = 7, b = 2; System.out.println("int division: " + a / b); System.out.println("with a cast: " + (double) a / b); System.out.println("rounded: " + Math.round(price)); }}
Output
Widened: 7.0
Narrowed: 9
int division: 3
with a cast: 3.5
rounded: 10
Without a cast, Java won't put a double into an int. Run it. Possible lossy conversion. Java is warning you that information could be lost. Adding the cast tells Java you mean it.
Main.javajava
public class Main { public static void main(String[] args) { double price = 9.99; int pounds = price; }}
Output
Main.java:4: error: incompatible types: possible lossy conversion from double to int
int pounds = price;
^
1 error
error: compilation failed