JVM Knowledge

The arithmetic instructions compute a result that is typically a function of two values on the operand stack, pushing the result back on the operand stack. There are two main kinds of arithmetic instructions: those operating on integer values and those operating on floating-point values. Within each of these kinds, the arithmetic instructions are specialized to Java Virtual Machine numeric types. There is no direct support for integer arithmetic on values of the byte, short, and char types (§2.11.1), or for values of the boolean type; those operations are handled by instructions operating on type int. Integer and floating-point instructions also differ in their behavior on overflow and divide-by-zero. The arithmetic instructions are as follows:

  • Add: iadd, ladd, fadd, dadd.
  • Subtract: isub, lsub, fsub, dsub.
  • Multiply: imul, lmul, fmul, dmul.
  • Divide: idiv, ldiv, fdiv, ddiv.
  • Remainder: irem, lrem, frem, drem.
  • Negate: ineg, lneg, fneg, dneg.
  • Shift: ishl, ishr, iushr, lshl, lshr, lushr.
  • Bitwise OR: ior, lor.
  • Bitwise AND: iand, land.
  • Bitwise exclusive OR: ixor, lxor.
  • Local variable increment: iinc.
  • Comparison: dcmpg, dcmpl, fcmpg, fcmpl, lcmp.

The semantics of the Java programming language operators on integer and floating-point values (JLS §4.2.2, JLS §4.2.4) are directly supported by the semantics of the Java Virtual Machine instruction set.

The Java Virtual Machine does not indicate overflow during operations on integer data types. The only integer operations that can throw an exception are the integer divide instructions (idiv and ldiv) and the integer remainder instructions (irem and lrem), which throw an ArithmeticException if the divisor is zero.

The Java Virtual Machine does not indicate overflow or underflow during operations on floating-point data types. That is, floating-point instructions never cause the Java Virtual Machine to throw a run-time exception (not to be confused with an IEEE 754 floating-point exception). An operation that overflows produces a signed infinity; an operation that underflows produces a subnormal value or a signed zero; an operation that has no unique mathematically defined result produces NaN. All numeric operations with NaN as an operand produce NaN as a result.

Comparisons on values of type long (lcmp) perform a signed comparison.

Comparisons on values of floating-point types (dcmpg, dcmpl, fcmpg, fcmpl) are performed using IEEE 754 nonsignaling comparisons.