Java Tutorial · Java Basics · Lesson 8 of 37

Java Type Casting

Widening and narrowing conversions, and parsing strings to numbers.

Widening (automatic)

Converting a smaller type to a larger one happens automatically: byte → short → int → long → float → double.

Narrowing (manual)

Going the other way can lose data, so you must cast explicitly with (type):

Example 1
public class Main {
    public static void main(String[] args) {
        int whole = 42;
        double widened = whole;          // automatic
        double price = 9.99;
        int narrowed = (int) price;      // cuts off the decimals
        long big = 3_000_000_000L;
        int overflowed = (int) big;      // data loss!
        System.out.println(widened + " " + narrowed + " " + overflowed);
        System.out.println(7 / 2 + " " + (double) 7 / 2);
        System.out.println(Math.round(9.99));
    }
}

Output

42.0 9 -1294967296
3 3.5
10

Run this on your computer — see “Get Started” for setup.

Strings and numbers

Parse strings with Integer.parseInt() / Double.parseDouble(), and convert anything to a string with String.valueOf() or concatenation. Invalid input throws NumberFormatException:

Example 2
public class Main {
    public static void main(String[] args) {
        int n = Integer.parseInt("123");
        double d = Double.parseDouble("4.5");
        String s = String.valueOf(n + d);
        System.out.println(s);
        try {
            Integer.parseInt("12abc");
        } catch (NumberFormatException e) {
            System.out.println("Not a number: " + e.getMessage());
        }
    }
}

Output

127.5
Not a number: For input string: "12abc"

Run this on your computer — see “Get Started” for setup.

Test yourself

What does (int) 9.99 evaluate to?

  1. 9
  2. 10
  3. 9.99
  4. Compile error
Show answer

Answer: 9

Casting to int truncates toward zero; use Math.round() to round.