Skip to content
Tutorials Center
My learning

Topics

Lesson 13 of 201 ยท Variables and Types

Type Casting and Conversion

Learn Java type casting - automatic widening, narrowing casts and data loss, rounding vs truncating, converting int to String and back, and handling NumberFormatException.

Real programs constantly move values from one type to another. You read "42" from a text field and need the number 42. You divide two int totals and want a double average. You compute a double price and need whole cents as a long. Each of these is a type conversion, and Java is strict about them on purpose.

Java does some conversions for you automatically, when they can't lose information. For the risky ones, you must write a cast to show the compiler that you know what you're doing. Converting between numbers and text is a third kind entirely, handled by methods rather than casts. This lesson covers all three, plus the exact rules for what happens to values that don't fit.

Widening: automatic conversions

A widening conversion goes from a smaller type to a larger one. Java does it silently, because every value of the smaller type fits in the larger one:

TEXT
byte โ†’ short โ†’ int โ†’ long โ†’ float โ†’ double
              char โ†—

Any arrow chain works: a byte can widen to long, an int to double, and a char to int (giving its character code).

Java
int count = 42;
long bigCount = count;        // int โ†’ long, automatic
double average = count;       // int โ†’ double: 42.0
char letter = 'A';
int code = letter;            // char โ†’ int: 65

Widening also happens inside expressions. In count * 1.5, the int is widened to double before multiplying, so the result is a double. The full promotion rules are in Arithmetic Operators.

Widening can still lose precision

There's one catch the arrows hide. Converting int or long to float, or long to double, never loses the size of a number, but it can lose digits. A float keeps only about 7 significant digits and a double about 16, while an int can have 10 and a long 19:

Java Widening that silently rounds

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

123456789 comes back as 123456792. The compiler allows this because the value is still in range, but the low digits are rounded. Keep IDs, counts and timestamps in integer types, and don't route them through float or double.

Narrowing: casts you must write

A narrowing conversion goes the other way, from a larger type to a smaller one, and might lose information. Java won't do it silently:

Java
double price = 9.99;
int whole = price;            // error: incompatible types: possible lossy conversion from double to int
int whole = (int) price;      // OK: an explicit cast

A cast is the target type in parentheses in front of a value: (int) price. It tells the compiler "convert this, and I accept the consequences". So you need to know exactly what those consequences are.

Floating point to integer: truncation

Casting a double or float to an integer type drops the fraction, moving toward zero. It never rounds:

Java
(int) 3.99      // 3
(int) -3.99     // -3, not -4
(int) 0.5       // 0

If the value is too large for the target, the result saturates: it becomes the target's maximum or minimum. NaN becomes 0.

Java
(int) 3e10           // 2147483647 (Integer.MAX_VALUE)
(long) 3e10          // 30000000000: fits in a long
(int) Double.NaN     // 0

Integer to smaller integer: the high bits are cut off

Casting between integer types is different. Java keeps only the lowest bits that fit in the target and throws the rest away. For values outside the target's range, that produces numbers that look random:

Java Narrowing casts and data loss

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

(byte) 200 is -56 because a byte holds 256 different values: the cast effectively subtracts or adds 256 until the result lands in -128โ€ฆ127. You'll see why at the bit level in Bitwise and Shift Operators. The important lesson: a narrowing cast never fails and never warns. If the value might not fit, check first, or use Math.toIntExact(longValue), which throws an ArithmeticException instead of quietly producing garbage (see Working with Numbers).

A cast hides problems from the compiler; it doesn't solve them. Before writing (int), ask: can this value ever be outside the int range, or have a fraction I care about? If yes, check, round or use a wider type.

Rounding instead of truncating

When you want the nearest whole number, use the Math methods instead of a bare cast:

Method Result for 2.5 Result for -2.5 Returns
(int) x 2 -2 int (truncation)
Math.round(x) 3 -2 long for double, int for float
Math.floor(x) 2.0 -3.0 double
Math.ceil(x) 3.0 -2.0 double
Math.rint(x) 2.0 -2.0 double (ties go to the even number)

Math.round rounds halves up (toward positive infinity), so -2.5 becomes -2. Because Math.round(double) returns a long, you often see (int) Math.round(x). The Math class lesson covers these methods in detail.

Java Converting a price to cents

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

19.99 * 100 is actually 1998.9999999999998 in binary floating point, so the cast gives 1998 cents: a cent lost. Math.round gives the intended 1999. This is a real-world bug in shopping carts and invoices, and one more reason money belongs in BigDecimal or whole cents from the start.

Casting inside expressions

Where you put the cast matters, because a cast applies only to the value directly after it:

Java
int total = 17;
int count = 4;

double a = (double) total / count;    // 4.25: total becomes 17.0, then divides
double b = (double) (total / count);  // 4.0: int division first, then the cast
double c = total / count;             // 4.0: same as b

A cast binds more tightly than *, / and +. So (double) total / count means ((double) total) / count. Use extra parentheses when you need to cast a whole expression, as in (int) (price * 100).

Another rule surprises people: arithmetic on byte, short and char always produces an int. So this fails even though both values are bytes:

Java
byte a = 10;
byte b = 20;
byte sum = a + b;            // error: incompatible types: possible lossy conversion from int to byte
byte sum = (byte) (a + b);   // OK
a += b;                      // also OK: compound assignment includes a hidden cast

The hidden cast in += is convenient, but it can also overflow silently. Assignment and Increment Operators shows the trap.

Numbers to strings

Converting a number to text is always safe, and there are several ways:

Java
int n = 42;
String a = String.valueOf(n);     // "42": works for every primitive
String b = Integer.toString(n);   // "42"
String c = "" + n;                // "42": concatenation, common and fine
String d = n + " items";          // "42 items"
String hex = Integer.toHexString(255);        // "ff"
String bin = Integer.toBinaryString(5);       // "101"
String two = String.format("%.2f", 3.14159);  // "3.14"

String.valueOf is the most general choice: it has overloads for every primitive and for objects (it turns null into "null" instead of throwing). For formatting with a fixed number of decimals, commas or padding, see Formatting Strings.

Strings to numbers: parsing

Going from text to a number is called parsing, and it can fail, because the text might not be a number at all. Each wrapper class has a parse method:

Method Example Result
Integer.parseInt(s) Integer.parseInt("42") int 42
Long.parseLong(s) Long.parseLong("9000000000") long
Double.parseDouble(s) Double.parseDouble("3.5") double 3.5
Integer.parseInt(s, radix) Integer.parseInt("ff", 16) 255
Boolean.parseBoolean(s) Boolean.parseBoolean("true") true
Integer.valueOf(s) Integer.valueOf("42") an Integer object

Integer.valueOf returns a wrapper object instead of a primitive. Use parseInt when you want an int; the difference matters in Wrapper Classes and Autoboxing.

NumberFormatException

When the text isn't a valid number for the method, it throws a NumberFormatException. Some cases are obvious, and some catch people out:

Java What parseInt accepts and rejects

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Notice what fails: a leading space (" 42"), a decimal point ("3.5"), an empty string, a value beyond Integer.MAX_VALUE, thousands separators ("1,000") and hex digits without a radix ("ff"). Integer.parseInt is strict about whitespace, while Double.parseDouble quietly ignores leading and trailing spaces. Call strip() on user input before parsing so both behave the same.

Parsing user input safely

Input from people is never guaranteed to be a number. Wrap the parse in try/catch and decide what to do with bad input, such as asking again, using a default or reporting an error. The Input box below already holds three lines; edit them and run again:

Java Parse input with a fallback

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

IO.readln reads one line from standard input, as you saw in Reading User Input. Exceptions and try/catch get a full lesson in Exceptions and try-catch.

Characters, digits and strings

Converting characters trips people up, because a char is also a number:

Java
char digit = '7';
int code = digit;                         // 55: the character code, NOT 7
int value = digit - '0';                  // 7
int value2 = Character.getNumericValue(digit);   // 7
String text = String.valueOf(digit);      // "7"
char first = "7 apples".charAt(0);        // '7'
char fromInt = (char) ('0' + 7);          // '7'

The details are in Characters and Booleans.

A note on casting objects

Casts also exist for reference types: (String) someObject or (Dog) animal. They don't convert anything; they tell the compiler to treat an object as a more specific type, and fail at run time with a ClassCastException if the object isn't really that type. You can't cast between unrelated types like String and int: (int) "42" is a compile error, and parsing is the only way. Object casts and the modern instanceof pattern that replaces most of them are explained in Polymorphism and Method Overriding and Pattern Matching.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does IO.println((int) -7.9); print?

    Casting a double to int truncates toward zero, so the fraction is dropped and -7.9 becomes -7. Math.floor(-7.9) would give -8.0.
  2. 2. What is (byte) 130?

    Only the low 8 bits are kept. A byte wraps every 256 values, so 130 becomes 130 - 256 = -126. Narrowing casts never throw.
  3. 3. With int a = 7, b = 2;, which expression evaluates to 3.5?

    The cast applies to a alone, so the division is 7.0 / 2 = 3.5. In (double) (a / b), integer division runs first and gives 3, which becomes 3.0.
  4. 4. Which call throws a NumberFormatException?

    Integer.parseInt rejects any whitespace, so "12 " fails. Double.parseDouble trims spaces, and "7f" is valid hexadecimal with radix 16.
  5. 5. Why does float f = 123_456_789; store 1.23456792E8?

    The conversion is allowed automatically because the value is within the float range, but float has only about 7 significant digits, so the low digits are rounded.

Summary

  • Widening (byte โ†’ short โ†’ int โ†’ long โ†’ float โ†’ double, and char โ†’ int) is automatic; int/long to float and long to double can still round away digits.
  • Narrowing needs a cast like (int) x. Floating to integer truncates toward zero and saturates at the limits (NaN โ†’ 0); integer to smaller integer keeps only the low bits.
  • Casts never fail or warn, so check ranges yourself or use Math.toIntExact. Use Math.round to round instead of truncate.
  • A cast applies only to the value right after it: (double) a / b is not (double) (a / b). Arithmetic on byte, short and char produces int.
  • Turn numbers into text with String.valueOf, Integer.toString or concatenation.
  • Turn text into numbers with Integer.parseInt, Long.parseLong and Double.parseDouble; they throw NumberFormatException for bad input, so strip and catch.

Next: Local Variable Type Inference with var, where you'll let the compiler infer types for you and learn when that helps or hurts readability.