AI Hints
Home›Java Tutorial›char and boolean, Type Casting, Practice: A Simple Calculator
Java · Lesson 17 of 120

Type Casting

Converting between types.

⏱ 2 min read▶ Video at 21:49🎓 Free
Watch this lesson in the Java courseWatch on YouTube ↗Full Java course

Sometimes you need a value as a different type. Like turning a decimal into a whole number. That's called casting.

  • Change a value's type
  • Called casting
  • Sometimes automatic

Two directions

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.

Widening

  • int → doubleAutomaticNothing lost

Narrowing

  • double → intNeeds (int)Decimals cut off

Casting in action

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

Java asks you to cast

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

Summary

Small to big is automatic. Big to small needs a cast, which cuts off decimals. Use Math dot round to round. Next, a practice calculator.

Key takeaways
  • Widening: automatic
  • (int) cuts decimals
  • Math.round rounds
Next up: Practice: A Simple Calculator — put module two together