Java 中的算术运算符

原文: https://javabeginnerstutorial.com/core-java-tutorial/java-arithmetic-operator/

在本节中,我们将学习算术运算符优先级运算符关联

运算符优先级

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

运算符优先级表

运算符优先级(从高到低)
后缀expr++ expr—
一元++expr —expr +expr –expr ~ !
乘法 / %
加法+ –
移位<< >> >>>
关系< > <= >= instanceof
相等== !=
按位与&
按位异或^
按位或|
逻辑与&&
逻辑或||
三元?:
赋值= += -= = /= %= &= ^= |= <<= >>= >>>=

优先级示例

  1. /*
  2. * Here we will see the effect of precedence in operators life
  3. */
  4. class OperatorPrecedenceExample {
  5. public static void main(String args[]) {
  6. int i = 40;
  7. int j = 80;
  8. int k = 40;
  9. int l = i + j / k;
  10. /*
  11. * In above calculation we are not using any bracket. So which operator
  12. * will be evaluated first is decided by Precedence. As precedence of
  13. * divison(/) is higher then plus(+) as per above table so divison will
  14. * be evaluated first and then plus.
  15. *
  16. * So the output will be 42.
  17. */
  18. System.out.println("value of L :" + l);
  19. int m = (i + j) / k;
  20. /*
  21. * In above calculation brackets are used so precedence will not come in
  22. * picture and plus(+) will be evaluated first and then divison()/. So
  23. * output will be 3
  24. */
  25. System.out.println("Value of M:" + m);
  26. }
  27. }

运算符关联性

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

关联性示例

  1. package jbt.bean;
  2. /*
  3. * Here we will see the effect of precedence in operators life
  4. */
  5. public class OperatorAssociativityExample {
  6. public static void main(String args[]) {
  7. int i = 40;
  8. int j = 80;
  9. int k = 40;
  10. int l = i / k * 2 + j;
  11. /*
  12. * In above calculation we are not using any bracket. And there are two
  13. * operator of same precedence(divion and multiplication) so which
  14. * operator(/ or *) will be evaluated first is decided by association.
  15. * Associativity of * & / is left to right. So divison will be evaluated
  16. * first then multiplication.
  17. *
  18. * So the output will be 82.
  19. */
  20. System.out.println("value of L :" + l);
  21. int m = i / (k * 2) + j;
  22. /*
  23. * In above calculation brackets are used so associativity will not come
  24. * in picture and multiply(*) will be evaluated first and then
  25. * divison()/. So output will be 80
  26. */
  27. System.out.println("Value of M:" + m);
  28. }
  29. }

Java 中的运算符

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

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