# Java 中的算术运算符

> 原文： [https://javabeginnerstutorial.com/core-java-tutorial/java-arithmetic-operator/](https://javabeginnerstutorial.com/core-java-tutorial/java-arithmetic-operator/)

在本节中，我们将学习**算术**，**运算符**，**优先级**和**运算符关联**。

## 运算符优先级

*优先级*决定在同一计算中存在多个运算符的情况下，首先求值哪个运算符。

## 运算符优先级表

| 运算符 | 优先级（从高到低） |
| 后缀 | `expr++ expr--` |
| 一元 | `++expr --expr +expr –expr ~ !` |
| 可乘的 | `* / %` |
| 添加剂 | `+ –` |
| 转移 | `<< >> >>>` |
| 关系的 | `< > <= >= instanceof` |
| 平等 | `== !=` |
| 按位与 |`& |
| 按位异或 | `^` |
| 按位或 | <code>&#124;</code> |
| 逻辑与 | `&&` |
| 逻辑或 | <code>&#124;&#124;</code> |
| 三元 | `?:` |
| 分配 | <code>= += -= *= /= %= &= ^= &#124;= <<= >>= >>>=</code> |

## 优先示例

```java
/*
 * Here we will see the effect of precedence in operators life
 */
class OperatorPrecedenceExample {

	public static void main(String args[]) {
		int i = 40;
		int j = 80;
		int k = 40;

		int l = i + j / k;
		/*
		 * In above calculation we are not using any bracket. So which operator
		 * will be evaluated first is decided by Precedence. As precedence of
		 * divison(/) is higher then plus(+) as per above table so divison will
		 * be evaluated first and then plus.
		 *
		 * So the output will be 42.
		 */

		System.out.println("value of L :" + l);

		int m = (i + j) / k;
		/*
		 * In above calculation brackets are used so precedence will not come in
		 * picture and plus(+) will be evaluated first and then divison()/. So
		 * output will be 3
		 */

		System.out.println("Value of M:" + m);
	}
}
```

## 运算符关联

如果两个运算符在计算中具有相同的优先级，则将使用运算符的**关联性**来决定首先执行哪个运算符。

## 关联性示例

```java
package jbt.bean;

/*
 * Here we will see the effect of precedence in operators life
 */
public class OperatorAssociativityExample {

	public static void main(String args[]) {
		int i = 40;
		int j = 80;
		int k = 40;

		int l = i / k * 2 + j;
		/*
		 * In above calculation we are not using any bracket. And there are two
		 * operator of same precedence(divion and multiplication) so which
		 * operator(/ or *) will be evaluated first is decided by association.
		 * Associativity of * & / is left to right. So divison will be evaluated
		 * first then multiplication.
		 *
		 * So the output will be 82.
		 */

		System.out.println("value of L :" + l);

		int m = i / (k * 2) + j;
		/*
		 * In above calculation brackets are used so associativity will not come
		 * in picture and multiply(*) will be evaluated first and then
		 * divison()/. So output will be 80
		 */

		System.out.println("Value of M:" + m);
	}

}
```

## Java 中的运算符

让我们分别讨论每个运算符。

赋值（`=`）和算术运算符（`+, -, *, /`）的工作方式与其他编程语言相同，因此在此不再赘述。 `/`和`*`运算符的优先级高于加法（`+`）或减法（`-`）或取模（`%`）

