Java operators precedence table

Java Operator Precedence

Before you start reading this article, you should have a basic knowledge of Java Operators.

Now, take a look at the statement below:

What will be the value of myInt ? Will it be (12 — 4)*2 , that is, 16 ? Or it will be 12 — (4 * 2) , that is, 4 ?

When two operators share a common operand, 4 in this case, the operator with the highest precedence is operated first.

In Java, the precedence of * is higher than that of — . Hence, the multiplication is performed before subtraction, and the value of myInt will be 4.

Operator Precedence Table

The table below lists the precedence of operators in Java; higher it appears in the table, the higher its precedence.

Java Operator Precedence

Operators Precedence
postfix increment and decrement ++ —
prefix increment and decrement, and unary ++ — + — ~ !
multiplicative * / %
additive + —
shift > >>>
relational < >= instanceof
equality == !=
bitwise AND &
bitwise exclusive OR ^
bitwise inclusive OR |
logical AND &&
logical OR ||
ternary ? :
assignment = += -= *= /= %=
&= ^= |= <>= >>>=

Example: Operator Precedence

The operator precedence of prefix ++ is higher than that of — subtraction operator. Hence,

Читайте также:  Add data attribute javascript

When dealing with multiple operators and operands in a single expression, you can use parentheses like in the above example for clarity. The expression inside the parentheses is evaluated first.

Associativity of Operators in Java

If an expression has two operators with similar precedence, the expression is evaluated according to its associativity (either left to right, or right to left). Let’s take an example.

Here, the value of c is assigned to variable b . Then the value of b is assigned of variable a . Why? It’s because the associativity of = operator is from right to left.

The table below shows the associativity of Java operators along with their associativity.

Java Operator Precedence and Associativity

Operators Precedence Associativity
postfix increment and decrement ++ — left to right
prefix increment and decrement, and unary ++ — + — ~ ! right to left
multiplicative * / % left to right
additive + — left to right
shift > >>> left to right
relational < >= instanceof left to right
equality == != left to right
bitwise AND & left to right
bitwise exclusive OR ^ left to right
bitwise inclusive OR | left to right
logical AND && left to right
logical OR || left to right
ternary ? : right to left
assignment = += -= *= /= %=
&= ^= |= <>= >>>=
right to left

You don’t need to memorize everything here. Most of the time, the precedence and associativity of operators makes sense in itself. You can always come back to this article for reference when in doubt. Also, you can use parenthesis if you think it makes your code easier to understand.

Table of Contents

Источник

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.

Источник

Operators

Now that you've learned how to declare and initialize variables, you probably want to know how to do something with them. Learning the operators of the Java programming language is a good place to start. Operators are special symbols that perform specific operations on one, two, or three operands, and then return a result.

As we explore the operators of the Java programming language, it may be helpful for you to know ahead of time which operators have the highest precedence. The operators in the following table are listed according to precedence order. The closer to the top of the table an operator appears, the higher its precedence. Operators with higher precedence are evaluated before operators with relatively lower precedence. Operators on the same line have equal precedence. When operators of equal precedence appear in the same expression, a rule must govern which is evaluated first. All binary operators except for the assignment operators are evaluated from left to right; assignment operators are evaluated right to left.

Operator Precedence

Operators Precedence
postfix expr++ expr--
unary ++expr --expr +expr -expr ~ !
multiplicative * / %
additive + -
shift > >>>
relational < >= instanceof
equality == !=
bitwise AND &
bitwise exclusive OR ^
bitwise inclusive OR |
logical AND &&
logical OR ||
ternary ? :
assignment = += -= *= /= %= &= ^= |= <>= >>>=

In general-purpose programming, certain operators tend to appear more frequently than others; for example, the assignment operator " = " is far more common than the unsigned right shift operator " >>> ". With that in mind, the following discussion focuses first on the operators that you're most likely to use on a regular basis, and ends focusing on those that are less common. Each discussion is accompanied by sample code that you can compile and run. Studying its output will help reinforce what you've just learned.

Previous page: Questions and Exercises: Variables
Next page: Assignment, Arithmetic, and Unary Operators

Источник

Operator Precedence in Java Programming

In this lesson, we will learn what is the rule of Operator Precedence in Java programming and how it works with some examples.

What is Operator Precedence

Operator Precedence in Java programming is a rule that describe which operator is solved first in an expression. For example: * and / have same precedence and their associativity is Left to Right, so the expression 18 / 2 * 5 is treated as (18 / 2) * 5.

Let's take another example say x = 8 + 4 * 2; here value of x will be 16 and not 24 why, because * operator has a higher precedence than + operator. So 4*2 gets multiplied first and then adds into 8.

Operator Associativity means how operators of the same precedence are evaluated in an expression. Associativity can be either from left to right or right to left.

The table below shows all the operators in Java with precedence and associativity.

video-poster

Precedence and Associativity of Java Operators

OPERATOR DESCRIPTION ASSOCIATIVITY
( )
[ ].
Parentheses
Array Subscript
Member Selector
left to right
++
--
Post-Increment
Post-Decrement
right to left
++
--
+
-
!
~
(type)
new
Pre-Increment
Pre-Decrement
Unary Plus
Unary Minus
Unary Logical Negation
Unary Bitwise Complement
Unary Cast
Object Creation
right to left
* / % Multiplication, Division and Modulus left to right
+ - Addition and Subtraction left to right
> Bitwise leftshift and right shift left to right
< > >= relational less than / less than or equal to
relational greater than / greater than or equal to
left to right
== != Relational equal to / not equal to left to right
& Bitwise AND left to right
^ Bitwise exclusive OR left to right
| Bitwise inclusive OR left to right
&& Logical AND left to right
|| Logical OR left to right
? : Ternary operator right to left
=
+= -=
*= /=
%= &=
^= |=
>=
>>>
Assignment operator
Addition / subtraction assignment
Multiplication / division assignment
Modulus and bitwise assignment
Bitwise exclusive / inclusive OR assignment
Bitwise leftshift / rightshift assignment
Bitwise right shift with zero extension
right to left

Please don't get confused after seeing the above table. They all are used in a different situation but not all at the same time. For solving basic equation we will consider the following operator precedence only.

  • ( ) Brackets will be solved first.
  • * / % Which ever come first from left to right in your equation.
  • + - Which ever come first from left to right in your equation.

Now let's see some examples for more understanding.

Example 1

45 % 2 + 3 * 2 45 % 2 + 3 * 2 will be solved as per operator precedence rule 1 + 3 * 2 will be solved as per operator precedence rule 1 + 6 will be solved as per operator precedence rule 7 (Answer)

Example 2

19 + (5 / 2) + 4 % 2 - 6 * 3 19 + (5 / 2) + 4 % 2 - 6 * 3 will be solved as per operator precedence rule 19 + 2 + 4 % 2 - 6 * 3 will be solved as per operator precedence rule 19 + 2 + 0 - 6 * 3 will be solved as per operator precedence rule 19 + 2 + 0 - 18 will be solved as per operator precedence rule 21 + 0 - 18 will be solved as per operator precedence rule 21 - 18 will be solved as per operator precedence rule 3 (Answer)

Test Your Knowledge

Attempt the multiple choice quiz to check if the lesson is adequately clear to you.

Источник

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