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.
int count = 42; int big = 1_000_000; // underscores are allowed in literals int mask = 0xFF; // hexadecimal
Try it
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.
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
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 tolongorBigInteger. - Integer division truncates.
1 / 2is0. Convert one operand first (1.0 / 2or(double) a / b) when you want a fraction. Casting after the division is too late. - Remainder keeps the dividend's sign.
-7 % 3is-1. UseMath.floorMod()for a result that is never negative. - Mixed arithmetic promotes.
byte,shortandcharoperands are widened tointbefore the operation, so the result ofa + bon two shorts is anint. - Compound assignment hides a cast.
short s = 1; s += 100000;compiles and narrows the result, whiles = s + 100000;does not. - A leading zero means octal.
010is 8. Avoid leading zeros in decimal literals. - Boxing. A
List<Integer>storesIntegerobjects, notintvalues. Compare boxed values withequals(), never==; see autoboxing. intis the right default for indexes and counts. Array lengths andString.length()areint, so collections cannot exceed about 2.1 billion elements.- Reading values larger than the range with
Integer.parseInt()throwsNumberFormatException.