Chapter 2 · Simulation

Primitive Types Lab

← Chapter 2
Java code
Output

Bit level

Primitive Types Lab

Purpose: see, at the value level and the bit level, how Java's seven numeric primitive types (byte, short, char, int, long, float, double) behave in an expression.

How to use it

  1. Pick a preset example, or set the type and value of the variables a and b, the operation, and the type of the variable r that receives the result. For char, type a single character.
  2. If explicit cast (type) is checked, the expression is converted with (type) before it is assigned; otherwise only an implicit widening is allowed and a narrowing is a compile error.
  3. The code, output, explanation and bit level update on every change: a, b, the value of the expression and r. In a narrowing, the discarded high bits appear faded and struck through; for float/double, the sign, exponent and significand have separate colors.
  4. While Try it yourself is on, the output is hidden; you guess by choosing one of the options.

Rules

  • Numeric promotion: in binary arithmetic, byte, short and char are first promoted to int; if one operand is long, float or double, the expression is computed in that type. That is why byte + byte is an int.
  • Overflow: if an integer result does not fit its type, there is no error; the extra bits are discarded and the value wraps around (Integer.MAX_VALUE + 1 → -2147483648). Overflow happens before the result is assigned to a wider variable.
  • Integer division discards the fractional part (toward zero); in % the sign of the result is the sign of the dividend. Dividing an integer by zero throws ArithmeticException; for float/double the result is Infinity or NaN.
  • Widening (e.g. int → long) is implicit; int/long → float and long → double are widening conversions but may round. Narrowing (e.g. int → byte) needs an explicit cast such as (byte): for integers only the low bits are kept; converting a floating-point number to an integer drops the fractional part, clamps out-of-range values to the largest or smallest value, and turns NaN into 0. byte ↔ char and short ↔ char need an explicit cast in both directions.
  • char is a 16-bit unsigned number: 'A' + 1 = 66 (int), (char) ('A' + 1) = B. Printing a char variable shows the character; printing a numeric variable shows the number.

All the outputs and compile errors shown were verified against the output of javac --release 8 + java for the examples and for thousands of random inputs. Non-printable characters (control characters) are shown by their codes.

Related slides: Chapter 2.2 · Syntax Rules.