Concepts / Java Numeric Types

Java Numeric Types

Assignment is an operator whose value is the value assigned to the left-hand variable.

  • Programming

When a Simple Assignment Surprises You

Numeric values in Java seem simple until a program produces a result you did not expect. A variable receives a number, the number is printed, and the printed value is wrong, or a decimal quietly loses its fractional part. Most of these surprises come from two ideas that beginners often merge: computing a value, and making that value fit the type of the variable that will store it. This article separates those two ideas so you can locate where a numeric value changes and why.

What do you think happens?

What do you think the variable s holds after this code runs: int big = 100000; short s = (short) big;

Reveal answer
Answer:

s holds -31072

The cast asks Java to store 100000 in a short. The short type cannot represent 100000, so the stored numeric value changes. The source gives this exact case: (short)100000 produces -31072.

Assignment as an Operator

Definition

Assignment is an operator whose value is the value assigned to the left-hand variable.

A common first impression is that the equals sign only records a value in a variable. In Java, the equals sign also acts as an operator. An assignment has a value of its own, which is the value assigned to the variable on the left. Because of this, an assignment can appear inside a larger expression. Combining assignment with other tests can make a program harder to read, so use this feature with care.

java
Output
5 5
Notes on the code
  • b = 5 is evaluated first; it stores 5 in b and its value is 5
  • That value becomes the right-hand side of a = ...; a receives 5
  • Both variables hold 5 when the print statement runs

Automatic Widening Conversions

Java converts numeric values automatically in one permitted direction, running from byte through double. Moving a value to a type that can hold it without losing its meaning requires no request from you. The order of the numeric types is byte, short, int, long, float, double. When a value moves rightward through that list into a wider type, Java performs the conversion for you during assignment.

byteshortintlongfloatdoublewidens towidens towidens towidens towidens to
Which numeric conversions does Java perform automatically, and in which direction does the order run?
java
Output
42.0
Notes on the code
  • count is an int, and double is further along the widening order
  • Java converts the int to a double during assignment without an explicit cast
  • The printed value shows the decimal form of the double

The char type is closely related to integer types. A char value can be assigned to an int variable, and an integer constant from 0 through 65535 can be assigned to a char variable. Explicit casts can also move between char and numeric types.

Explicit Casts and What They Discard

When an automatic conversion is not permitted, or when you want a conversion Java would not perform on its own, you request it with an explicit cast. The cast places the target type in parentheses in front of the value. A cast can force Java to use a representation that cannot preserve all of the original information. Two cases in the source matter most. Casting a real number to int removes its fractional part. Casting a numeric value to a smaller numeric type can change the numeric value when the original lies outside the target type's range.

java
Output
3
Notes on the code
  • (int) is the explicit cast; int is written in parentheses before the value
  • The fractional part .9 is removed rather than rounded
  • The result is an int holding 3
Worked example

Tracing a Narrowing Cast

Trace what value is stored when the int 100000 is cast to a short.

  1. 1
    Ask what value the expression produces

    The expression (short) big produces a value of type short built from the int 100000.

  2. 2
    Check whether the value fits the target

    100000 lies outside the range that a short can represent, so the numeric value must change.

  3. 3
    Accept the stored result

    The source states that (short)100000 produces -31072. The cast made the stored value differ from the original.

Result

The variable s holds -31072, not 100000.

Mistakes With Assignment and Casts

  • Common mistake

    Assuming a cast rounds a decimal value

    What it looks like
    double d = 3.9; int i = (int) d;
    Why it fails

    A cast from a real number to int removes the fractional part. It does not round.

    Do this instead

    Expect the result 3. If you need rounding, that is a separate operation and is not what the cast does.

  • Common mistake

    Expecting a narrowing cast to keep the value

    What it looks like
    int big = 100000; short s = (short) big;
    Why it fails

    A cast to a smaller type can change the numeric value when the original lies outside the target range.

    Do this instead

    Check that the value fits the destination type before casting, or choose a wider type.

  • Common mistake

    Judging the assignment without evaluating the right side first

    Why it fails

    An assignment can fail in two stages: the expression on the right produces a value, and then that value must be stored in the variable on the left without an unrequested conversion.

  • Common mistake

    Using a cast to convert a String to a number

    What it looks like
    int n = (int) "42";
    Why it fails

    A type cast is not the mechanism for converting between String and other types.

    Do this instead

    Use Integer.parseInt("42") to interpret the text as an int.

Converting Between Strings and Numbers

String conversion is handled differently from numeric casting. A cast does not convert between String and numeric values. Instead, Java provides specific methods. To produce a String from a value, use String.valueOf(x). To interpret a String as an int, use Integer.parseInt(str). To interpret a String as a double, use Double.parseDouble(str). The parsing methods report an error when the text does not represent a legal value of the requested type.

java
Output
42 42 3.5
Notes on the code
  • String.valueOf turns the number 42 into the String "42"
  • Integer.parseInt reads the text "42" as an int
  • Double.parseDouble reads the text "3.5" as a double
GoalMethodDirection
Number to StringString.valueOf(x)Produces text from a value
String to intInteger.parseInt(str)Interprets text as an int
String to doubleDouble.parseDouble(str)Interprets text as a double
Between numeric typesCast such as (int) valueRequests a numeric conversion, possibly losing information

Choosing the right conversion method

Checking Your Understanding

MEDIUM

Predict the value of y after this code runs: int x; int y; x = y = 7; double z = (double) x; y = (int) 2.8; What is the final value of y, and what is the value of the expression y = (int) 2.8 by itself?

Hints
  • An assignment expression has the value of the variable on its left.
  • A cast from a real number to int removes the fractional part.
EASY

Write a short Java snippet that starts with the String "120", converts it to an int, then casts a double value 7.99 to an int and adds the two results. State which method you chose for each conversion and why a cast was not used for the String.

Hints
  • Use Integer.parseInt for text, and an explicit cast for the numeric conversion.
  • The cast drops the fractional part, so 7.99 becomes 7.

Key Takeaways

  • An assignment is an operator whose value is the value assigned to the left-hand variable, so it can be used inside a larger expression.
  • Java converts numeric values automatically in the permitted direction from byte through double, but never requires a cast for that widening direction.
  • An explicit cast requests a conversion that may discard information: a real number cast to int loses its fractional part, and a value outside the target range can change, as in (short)100000 producing -31072.
  • Use String.valueOf to produce a String, Integer.parseInt to read an int from text, and Double.parseDouble to read a double from text, because casts do not handle String conversion.