整数运算
1. 整数四则运算
Java 的整数运算遵循常规四则运算规则,并且可以使用任意层级的小括号。
示例:
1 2 3 4 5 6 7 8
| public class Main { public static void main(String[] args) { int i = (100 + 200) * (99 - 88); int n = 7 * (5 + (i - 9)); System.out.println(i); System.out.println(n); } }
|
整数运算 永远精确,包括除法:
求余使用 %:
⚠ 注意:当除数为 0 时,运行时会报错(ArithmeticException),但编译不会报错。
2. 整数溢出(Overflow)
Java 的 int 和 long 都有范围限制。超过范围不会报错,而是溢出:
1 2 3 4
| int x = 2147483640; int y = 15; int sum = x + y; System.out.println(sum);
|
原因:符号位被进位影响。
解决方式:使用范围更大的 long:
1 2 3
| long x = 2147483640L; long y = 15; long sum = x + y;
|
3. 复合赋值运算符
等价写法:
1 2 3 4
| n += 100; n -= 100; n *= 2; n /= 4;
|
4. 自增 / 自减运算
Java 提供 ++ 和 --:
1 2 3
| int n = 3300; n++; n--;
|
区别示例:
1 2
| int y = 100 + (++n); int z = 100 + (n++);
|
⚠ 建议:不要将 ++ 或 – 混入复杂表达式中,容易出错。
5. 移位运算(Shift Operations)
整数以二进制存储,例如:
1
| 7 = 00000000 00000000 00000000 00000111
|
5.1 左移 <<(乘 2)
1 2 3 4 5
| int n = 7; int a = n << 1; int b = n << 2; int c = n << 28; int d = n << 29;
|
5.2 右移 >>(除 2,带符号)
1 2 3 4
| int n = 7; int a = n >> 1; int b = n >> 2; int c = n >> 3;
|
负数右移保持符号位:
1 2 3 4 5
| int n = -536870912; int a = n >> 1; int b = n >> 2; int c = n >> 28; int d = n >> 29;
|
5.3 无符号右移 >>>
高位补 0,因此适合用于二进制处理:
1 2 3 4 5
| int n = -536870912; int a = n >>> 1; int b = n >>> 2; int c = n >>> 29; int d = n >>> 31;
|
⚠ 对 byte 和 short 进行移位时,会 先转换成 int 再移位。
6. 位运算(Bitwise Operations)
按位操作 0/1。
| 运算符 |
名称 |
说明 |
& |
与 AND |
必须两个数同时为1,结果才为1 |
| ` |
` |
或 OR |
~ |
非 NOT |
0 和 1 互换 |
^ |
异或 XOR |
如果两个数不同,结果为1,否则为0 |
Java没有单个bit的数据类型。在Java中,对两个整数进行位运算,实际上就是按位对齐,然后依次对每一位进行运算。例如:
1 2 3 4 5 6 7 8 9 10
| public class Main { public static void main(String[] args) { int i = 167776589; int n = 167776512; System.out.println(i & n); } }
|
常用于判断 IP 是否属于某网段等系统编程场景。
7. 运算优先级(从高到低)
1 2 3 4 5 6 7 8
| () ! ~ ++ -- * / % + - << >> >>> & | += -= *= /=
|
记不住也没关系 → 只需要加括号就可以保证运算的优先级正确。
8. 类型自动提升与强制转型
8.1 自动提升
当不同类型参与运算时,结果会提升为“更大范围的类型”:
1 2 3 4 5 6 7 8
| public class Main { public static void main(String[] args) { short s = 1234; int i = 123456; int x = s + i; } }
|
以下写法会报错:
8.2 强制转型(可能损失数据)
1 2
| int i = 12345; short s = (short) i;
|
要注意,超出范围的强制转型会得到错误的结果,原因是转型时,int的两个高位字节直接被扔掉,仅保留了低位的两个字节:
1 2 3 4 5 6 7 8 9 10 11
| public class Main { public static void main(String[] args) { int i1 = 1234567; short s1 = (short) i1; System.out.println(s1); int i2 = 12345678; short s2 = (short) i2; System.out.println(s2); } }
|
原因:int 的高位直接丢弃,只保留低 16 bit。
9. 练习:计算前 N 个自然数的和
公式:
示例:
1 2 3 4 5 6 7 8 9 10
| public class Main { public static void main(String[] args) { int n = 100; int sum = ???; System.out.println(sum); System.out.println(sum == 5050 ? "测试通过" : "测试失败"); } }
|
10. 小结
- 整数运算是 精确的,包括除法(但只保留整数部分)。
- 运算中不同类型会进行 自动类型提升。
- 强制转型可能导致 数据截断或溢出。
- 应选择合适的数据类型(一般用
int 或 long)。
- 移位运算可理解为 ×2 或 ÷2 操作。
- 多使用括号避免运算优先级问题。