---
spec: JVMS
title: "The Java Virtual Machine Specification"
edition: "Java SE 11 Edition"
java_version: 11
chapter: "Chapter 3. Compiling for the Java Virtual Machine"
section: "3.3"
heading: "3.3. Arithmetic"
parent: "Chapter 3. Compiling for the Java Virtual Machine"
source: https://docs.oracle.com/javase/specs/jvms/se11/html/jvms-3.html#jvms-3.3
id: "3.3"
url: https://jvm.obfuscated.software/jvms/se11/3.3.html
raw: https://jvm.obfuscated.software/jvms/se11/3.3.md
---

# 3.3. Arithmetic

The Java Virtual Machine generally does arithmetic on its operand stack. (The exception is the *iinc* instruction, which directly increments the value of a local variable.) For instance, the `align2grain` method aligns an `int` value to a given power of 2:

```
int align2grain(int i, int grain) {
    return ((i + grain-1) & ~(grain-1));
}
```

Operands for arithmetic operations are popped from the operand stack, and the results of operations are pushed back onto the operand stack. Results of arithmetic subcomputations can thus be made available as operands of their nesting computation. For instance, the calculation of `~(grain-1)` is handled by these instructions:

```
5   iload_2        // Push grain
6   iconst_1       // Push int constant 1
7   isub           // Subtract; push result
8   iconst_m1      // Push int constant -1
9   ixor           // Do XOR; push result
```

First `grain-1` is calculated using the contents of local variable *2* and an immediate `int` value `1`. These operands are popped from the operand stack and their difference pushed back onto the operand stack. The difference is thus immediately available for use as one operand of the *ixor* instruction. (Recall that `~x == -1^x`.) Similarly, the result of the *ixor* instruction becomes an operand for the subsequent *iand* instruction.

The code for the entire method follows:

```
Method int align2grain(int,int)
0   iload_1
1   iload_2
2   iadd
3   iconst_1
4   isub
5   iload_2
6   iconst_1
7   isub
8   iconst_m1
9   ixor
10  iand
11  ireturn
```
