Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Contents

Type conversion

Sometimes a value of one type has to become another: a whole number a fractional one, a fractional number a whole one, the string "42" a number. Java does some conversions on its own; others you have to ask for explicitly.

Automatic widening

When a value goes into a type that holds more, Java converts it by itself. This is called widening: int → long → double. No data is lost:

void main() {
    int count = 42;
    long big = count;
    double precise = count;
    IO.println(big);
    IO.println(precise);
}

Output:

42
42.0

Explicit casts

The other direction is risky: the fractional part or high digits can be lost. So Java requires an explicit cast — the type in parentheses before the value:

void main() {
    double price = 9.99;
    int whole = (int) price;
    IO.println(whole);
}

Output:

9

Casting to int drops the fractional part rather than rounding. For rounding there is Math.round(): Math.round(9.99) returns 10. And when a large whole number is cast to a smaller type, the high bits are dropped: (byte) 200 gives -56. Other math methods and exact money calculations are covered in the Math and BigDecimal lesson.

Fractional division

A cast helps get a fractional result from two whole numbers. Cast one of them to double before dividing:

void main() {
    int done = 7;
    int total = 8;
    double part = (double) done / total;
    IO.println(part);
}

Output:

0.875

Characters and numbers

Every char is stored as a number — its code in the Unicode table. A cast shows the code and turns a code back into a character:

void main() {
    char letter = 'A';
    IO.println((int) letter);
    IO.println((char) 66);
}

Output:

65
B

Strings and numbers

A string of digits cannot be cast with parentheses — there are the Integer.parseInt() and Double.parseDouble() methods for that. In the other direction, String.valueOf() turns a number into a string:

void main() {
    int quantity = Integer.parseInt("3");
    double price = Double.parseDouble("2.5");
    IO.println(quantity * price);
 
    String text = String.valueOf(100);
    IO.println(text + "!");
}

Output:

7.5
100!

You need these conversions all the time: everything a user types or a file contains starts out as a string.

Common mistake

If the string has even one extra character, parseInt() throws an exception — an error signal that stops the program:

void main() {
    int age = Integer.parseInt("25 years");
    IO.println(age);
}

Output:

Exception in thread "main" java.lang.NumberFormatException: For input string: "25 years"

Spaces count as extra characters too. The chapter on errors shows how to catch exceptions so the program does not crash.

Thanks for reading!

Donate to the site — we work hard for you.