Logical operators priority java

Java Operators: Precedence and Associativity

A Java operator is a special symbol that performs specific operation on one, two, or three operands depending upon the type of the operator and returns a result.

Java provides a rich set of operators that are classified on two bases. First, on the basis of number of operands an operator performs upon. Second, on the type or nature of operation an operator performs.

By first classification, Java operators can be unary, binary, or ternary. Unary operators operate on one operand e.g., ++ , and — . Binary operators operator on two operands. All arithmetic operators are example of binary operators. Third, special type operator is ternary operator. Ternary operator operates on three operands. Java has only one ternary operator, which is also called conditional operator. It is a combination of two symbols ? and : .

Another classification is based on the type of operation they perform. On the basis of the type of operation operators can be classified in following categories:

Evaluation Order of an Expression

In Java when an expression is evaluated, there may be more than one operators involved in an expression. When more than one operator has to be evaluated in an expression Java interpreter has to decide which operator should be evaluated first. Java makes this decision on the basis of the precedence and the associativity of the operators.

Читайте также:  Python list mean value

Java Operators Precedence and Associativity

Java operators have two properties those are precedence, and associativity. Precedence is the priority order of an operator, if there are two or more operators in an expression then the operator of highest priority will be executed first then higher, and then high. For example, in expression 1 + 2 * 5, multiplication (*) operator will be processed first and then addition. It’s because multiplication has higher priority or precedence than addition.

Alternatively, you can say that when an operand is shared by two operators (2 in above example is shared by + and *) then higher priority operator picks the shared operand for processing. From above example you would have understood the role of precedence or priority in execution of operators. But, the situation may not be as straightforward every time as it is shown in above example. What if all operators in an expression have same priority? In that case the second property associated with an operator comes into play, which is associativity. Associativity tells the direction of execution of operators that can be either left to right or right to left. For example, in expression a = b = c = 8 the assignment operator is executed from right to left that means c will be assigned by 8, then b will be assigned by c, and finally a will be assigned by b. You can parenthesize this expression as (a = (b = (c = 8))) .

Note that, you can change the priority of a Java operator by enclosing the lower order priority operator in parentheses but not the associativity. For example, in expression (1 + 2) * 3 addition will be done first because parentheses has higher priority than multiplication operator.

Читайте также:  Вывести количество элементов массива javascript

Before discussing individual classes of operators, below table presents all Java operators from highest to lowest precedence along with their associativity.

Table 1: Java operators — precedence chart highest to lowest
Precedence Operator Description Associativity
1 []
()
.
array index
method call
member access
Left -> Right
2 ++

+ —
~
!
pre or postfix increment
pre or postfix decrement
unary plus, minus
bitwise NOT
logical NOT
Right -> Left
3 (type cast)
new
type cast
object creation
Right -> Left
4 *
/
%
multiplication
division
modulus (remainder)
Left -> Right
5 + —
+
addition, subtraction
string concatenation
Left -> Right
6 >>
>>>
left shift
signed right shift
unsigned or zero-fill right shift
Left -> Right
7 <
>
>=
instanceof
less than
less than or equal to
greater than
greater than or equal to
reference test
Left -> Right
8 ==
!=
equal to
not equal to
Left -> Right
9 & bitwise AND Left -> Right
10 ^ bitwise XOR Left -> Right
11 | bitwise OR Left -> Right
12 && logical AND Left -> Right
13 || logical OR Left -> Right
14 ? : conditional (ternary) Right -> Left
15 =
+=
-=
*=
/=
%=
&=
^=
|=
<>>=
>>>=
assignment and short hand assignment operators Right -> Left

Last Word

In this tutorial we talked of Java operators’ precedence and associativity. Hope you have enjoyed reading this tutorial. Please do write us if you have any suggestion/comment or come across any error on this page. Thanks for reading!

References

Источник

Appendix A: Operator Precedence in Java

Java has well-defined rules for evaluating expressions, including operator precedence, operator associativity, and order of operand evalution. We describe each of these three rules.

Operator precedence.

Operator precedence specifies the manner in which operands are grouped with operators. For example, 1 + 2 * 3 is treated as 1 + (2 * 3), whereas 1 * 2 + 3 is treated as (1 * 2) + 3 because the multiplication operator has a higher precedence than the addition operator. You can use parentheses to override the default operator precedence rules.

Operator associativity.

When an expression has two operators with the same precedence, the operators and operands are grouped according to their associativity. For example 72 / 2 / 3 is treated as (72 / 2) / 3 since the division operator is left-to-right associate. You can use parentheses to override the default operator associativity rules.

You’ll find different (and usually equivalent) operator precedence tables on the web and in textbooks. They typically disagree in inconsequential ways because some operators cannot share operands, so their relative precedence order does not matter (e.g, new and ! ). There is no explicit operator precedence table in the Java Language Specification. Instead, the operator precedence and associativity rules are inferred via the grammar that defines the Java language.

Order of operand evaluation in Java.

Associativity and precedence determine in which order Java groups operands and operators, but it does not determine in which order the operands are evaluated. In Java, the operands of an operator are always evaluated left-to-right. Similarly, argument lists are always evaluated left-to-right. So, for example in the expression A() + B() * C(D(), E()), the subexpressions are evaluated in the order A(), B(), D(), E(), and C(). Although, C() appears to the left of both D() and E(), we need the results of both D() and E() to evaluate C(). It is considered poor style to write code that relies upon this behavior (and different programming languages may use different rules).

Short-circuit evaluation. With three exceptions ( && , || , and ?: ), Java evaluates every operand of an operator before the operation is performed. For the logical AND ( && ) and logical OR ( || ) operators, Java evaluate the second operand only if it is necessary to resolve the result. This is known as short-circuit evaluation. It allows statements like if ((s != null) && (s.length() length() method only if s is not null ). Programmers rarely use the non short-circuiting versions (& and |) with boolean expressions.

Operator precedence gone awry.

Sometimes the precedence order defined in a language do not conform with mathematical norms. For example, in Microsoft Excel, -a^b is treated as (-a)^b instead of -(a^b) . So -3^2 evaluates to 9 instead of -9 , which is the value that most mathematicians would expect. Microsoft acknowledges this quirk as a “design choice.” One wonders whether the programmer was relying on the C precedence order in which unary operators have higher precedence than binary operators. This rule agrees with mathematical conventions for all C operators, but fails with the addition of the exponentiation operator. Once the order was established in Microsoft Excel 2.0, it could not easily be changed without breaking backward compatibility.

Operator associativity gone awry.

Sometimes the associativty of an operator is implemented left-to-right in one programming language but right-to-left in another. An alarming example is exponentiation. In Wolfram Alpha and Google Sheets, the exponentiation operator is right-to-left associative, so 2 ^ 2 ^ 3 is treated as 2 ^ (2 ^ 3) , which is 256. However, in Matlab and Excel, the exponentiation operator is left-to-right associative, so 2 ^ 2 ^ 3 is treated as as (2 ^ 2) ^ 3 , which is 64. Exponentiation is not a binary operator in Java.

Exercises.

System.out.println("1 + 2 = " + 1 + 2); System.out.println("1 + 2 abc"); System.out.println("abc" + 1 + 2);
year % 4 == 0 && year % 100 != 0 || year % 400 == 0

Answer: LeapYear.java shows a variety of equivalent expressions, including the following reasonable alternative:

((year % 4 == 0) && (year % 100 != 0)) || (year % 400 == 0)
boolean a = false; boolean b = false; boolean c = true; System.out.println(a == b == c);

Answer: It prints true . The equality operator is left-to-right associative, so a == b evaluates to true and this result is compared to c , whihc yields true .

Hint: The unary operators are right-to-left associative.

Answer: It leads to a compile-time error because Java parses -- as the pre-decrement operator (and not two unary minus operators).

int x = 5; int y = 10; int z = ++x * y--;

Last modified on March 10, 2022.

Copyright © 2000–2019 Robert Sedgewick and Kevin Wayne. All rights reserved.

Источник

Оцените статью