Skip to main content

Appendix A: Operator Precedence in Java

 

Appendix A: Operator Precedence in Java


Java has well-defined rules for specifying the order in which the operators in an expression are evaluated when the expression has several operators. For example, multiplication and division have a higher precedence than addition and subtraction. Precedence rules can be overridden by explicit parentheses.

Precedence order.

 When two operators share an operand the operator with the higher precedence goes first. For example, 1 + 2 * 3 is treated as 1 + (2 * 3), whereas 1 * 2 + 3 is treated as (1 * 2) + 3 since multiplication has a higher precedence than addition.

Associativity.

 When an expression has two operators with the same precedence, the expression is evaluated according to its associativity. For example x = y = z = 17 is treated as x = (y = (z = 17)), leaving all three variables with the value 17, since the = operator has right-to-left associativity (and an assignment statement evaluates to the value on the right hand side). On the other hand, 72 / 2 / 3 is treated as (72 / 2) / 3 since the / operator has left-to-right associativity. Some operators are not associative: for example, the expressions (x <= y <= z) and x++-- are invalid.

Precedence and associativity of Java operators.

 The table below shows all Java operators from highest to lowest precedence, along with their associativity. Most programmers do not memorize them all, and even those that do still use parentheses for clarity.


LevelOperatorDescriptionAssociativity
16[]
.
()
access array element
access object member
parentheses
left to right
15++
--
unary post-increment
unary post-decrement
not associative
14++
--
+
-
!
~
unary pre-increment
unary pre-decrement
unary plus
unary minus
unary logical NOT
unary bitwise NOT
right to left
13()
new
cast
object creation
right to left
12* / %multiplicativeleft to right
11+ -
+
additive
string concatenation
left to right
10<< >>
>>>
shiftleft to right
9< <=
> >=
instanceof
relationalnot associative
8==
!=
equalityleft to right
7&bitwise ANDleft to right
6^bitwise XORleft to right
5|bitwise ORleft to right
4&&logical ANDleft to right
3||logical ORleft to right
2?:ternaryright to left
1 =   +=   -=
*=   /=   %=
&=   ^=   |=
<<=  >>= >>>=
assignmentright to left

There is no explicit operator precedence table in the Java Language Specification. Different tables on the web and in textbooks disagree in some minor ways.

Order of evaluation of subexpressions.

 Associativity and precedence determine in which order Java applies operators to subexpressions but they do not determine in which order the subexpressions are evaluated. In Java, subexpressions are evaluated from left to right (when there is a choice). 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 circuiting. When using the conditional and and or operators (&& and ||), Java does not evaluate the second operand unless it is necessary to resolve the result. This allows statements like if (s != null && s.length() < 10) to work reliably. Programmers rarely use the non short-circuiting versions (& and |) with boolean expressions.

Precedence order gone awry.

 Sometimes the precedence order defined in a language do not conform with mathematical norms. For example, in Microsoft Excel, -a^b is interpreted as (-a)^b instead of -(a^b). So -1^2 is equal to 1 instead of -1, which is the values 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.

Exercises.

  1. What is the result of the following code fragment?
    int x = 5;
    int y = 10;
    int z = ++x * y--;
    
  2. What is the result of the following code fragment? Explain.
    System.out.println("1 + 2 = " + 1 + 2);
    System.out.println("1 + 2 = " + (1 + 2));
    
    Answer1 + 2 = 12 and 1 + 2 = 3, respectively. If either (or both) of the operands of the + operator is a string, the other is automatically cast to a string. String concatenation and addition have the same precedence. Since they are left-associative, the operators are evaluated left-to-right. The parentheses in the second statement ensures that the second + operator performs addition instead of string concatenation.
  3. Add parentheses to the following expression to make the order of evaluation more clear.
    year % 4 == 0 && year % 100 != 0 || year % 400 == 0
    
    AnswerLeapYear.java shows a variety of equivalent expressions, including the following reasonable alternative.
    ((year % 4 == 0) && (year % 100 != 0)) || (year % 400 == 0)
    
  4. What does the following code fragment print?
    System.out.println(1 + 2 + "abc");
    System.out.println("abc" + 1 + 2);
    

    Answer3abc and abc12, respectively. The + operator is left associative, whether it is string concatenation or addition.

Comments

Popular posts from this blog

Privacy Policy

Privacy Policy Privacy Policy Yajindra Gautam built the Gstatus app as an Ad Supported app. This SERVICE is provided by Yajindra Gautam at no cost and is intended for use as is. This page is used to inform visitors regarding my policies with the collection, use, and disclosure of Personal Information if anyone decided to use my Service. If you choose to use my Service, then you agree to the collection and use of information in relation to this policy. The Personal Information that I collect is used for providing and improving the Service. I will not use or share your information with anyone except as described in this Privacy Policy. The terms used ...

How To Pass / Return An Array In Java

  This Tutorial will Explain How to Pass an Array as an Argument to a Method and as a Return Value for the Method in Java with Examples: Methods or functions are used in Java to break the program into smaller modules. These methods are called from other functions and while doing so data is passed to and from these methods to the calling functions. The data passed from the calling function to the called function is in the form of arguments or parameters to the function. The data returned from the function is the return value. =>  Check Here To See A-Z Of Java Training Tutorials Here. Usually, all the primitive and derived types can be passed to and returned from the function. Likewise, arrays also can be passed to the method and returned from the method. In this tutorial, we will discuss how to pass arrays as an argument to a method and return the array from the method. What You Will Learn:  [ show ] Passing Array To The Method In Java Arrays can be passed to other meth...