Skip to content
Tutorials Center
My learning

Topics

Java Reference ยท Types and Literals

The int type

Reference for Java int: the 32-bit signed integer type, its range, literals, overflow behavior, integer division and the helper methods on Integer.

int is Java's default integer type: a 32-bit, signed, two's-complement number. It holds values from -2,147,483,648 to 2,147,483,647, which is plenty for counters, indexes and most everyday arithmetic. Integer literals like 42 are int unless they end in L.

Arithmetic on int never throws when it goes out of range. It silently wraps around, so Integer.MAX_VALUE + 1 is Integer.MIN_VALUE. Division of two ints truncates toward zero, and dividing by zero throws ArithmeticException.

Java
int count = 42;
int big = 1_000_000;      // underscores are allowed in literals
int mask = 0xFF;          // hexadecimal

Try it

Java Range, overflow and division

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.

Java Literals and Integer helpers

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.

Syntax

Java
int name;
int name = value;
int a = 1, b = 2;
Property Value
Size 32 bits
Minimum Integer.MIN_VALUE = -231 = -2,147,483,648
Maximum Integer.MAX_VALUE = 231 - 1 = 2,147,483,647
Default value (fields, array elements) 0
Wrapper class java.lang.Integer
Literal forms 42, 1_000, 0x2A, 052, 0b101010

Usage notes

  • Overflow is silent. Use Math.addExact(), Math.multiplyExact() and friends when wrapping would be a bug, or switch to long or BigInteger.
  • Integer division truncates. 1 / 2 is 0. Convert one operand first (1.0 / 2 or (double) a / b) when you want a fraction. Casting after the division is too late.
  • Remainder keeps the dividend's sign. -7 % 3 is -1. Use Math.floorMod() for a result that is never negative.
  • Mixed arithmetic promotes. byte, short and char operands are widened to int before the operation, so the result of a + b on two shorts is an int.
  • Compound assignment hides a cast. short s = 1; s += 100000; compiles and narrows the result, while s = s + 100000; does not.
  • A leading zero means octal. 010 is 8. Avoid leading zeros in decimal literals.
  • Boxing. A List<Integer> stores Integer objects, not int values. Compare boxed values with equals(), never ==; see autoboxing.
  • int is the right default for indexes and counts. Array lengths and String.length() are int, so collections cannot exceed about 2.1 billion elements.
  • Reading values larger than the range with Integer.parseInt() throws NumberFormatException.