4.2.2 Integer Operations

Java provides a number of operators that act on integral values:

Other useful constructors, methods, and constants are predefined in the classes Integer (§20.7), Long (§20.8), and Character (§20.5).

If an integer operator other than a shift operator has at least one operand of type long, then the operation is carried out using 64-bit precision, and the result of the numerical operator is of type long. If the other operand is not long, it is first widened (§5.1.2) to type long by numeric promotion (§5.6). Otherwise, the operation is carried out using 32-bit precision, and the result of the numerical operator is of type int. If either operand is not an int, it is first widened to type int by numeric promotion.

The built-in integer operators do not indicate overflow or underflow in any way. The only numeric operators that can throw an exception (§11) are the integer divide operator / (§15.16.2) and the integer remainder operator % (§15.16.3), which throw an ArithmeticException if the right-hand operand is zero.

The example:


class Test {
	public static void main(String[] args) {
		int i = 1000000;
		System.out.println(i * i);
		long l = i;
		System.out.println(l * l);
		System.out.println(20296 / (l - i));
	}
}

produces the output:


-727379968
1000000000000

and then encounters an ArithmeticException in the division by l - i, because l - i is zero. The first multiplication is performed in 32-bit precision, whereas the second multiplication is a long multiplication. The value -727379968 is the decimal value of the low 32 bits of the mathematical result, 1000000000000, which is a value too large for type int.

Any value of any integral type may be cast to or from any numeric type. There are no casts between integral types and the type boolean.