Читать книгу OCP Oracle Certified Professional Java SE 17 Developer Study Guide - Jeanne Boyarsky - Страница 132

Operator Precedence

Оглавление

When reading a book or a newspaper, some written languages are evaluated from left to right, while some are evaluated from right to left. In mathematics, certain operators can override other operators and be evaluated first. Determining which operators are evaluated in what order is referred to as operator precedence. In this manner, Java more closely follows the rules for mathematics. Consider the following expression:

var perimeter = 2 * height + 2 * length;

Let's apply some optional parentheses to demonstrate how the compiler evaluates this statement:

var perimeter = ((2 * height) + (2 * length));

The multiplication operator (*) has a higher precedence than the addition operator (+), so the height and length are both multiplied by 2 before being added together. The assignment operator (=) has the lowest order of precedence, so the assignment to the perimeter variable is performed last.

Unless overridden with parentheses, Java operators follow order of operation, listed in Table 2.1, by decreasing order of operator precedence. If two operators have the same level of precedence, then Java guarantees left-to-right evaluation for most operators other than the ones marked in the table.

TABLE 2.1 Order of operator precedence

Operator Symbols and examples Evaluation
Post-unary operators expression++, expression-- Left-to-right
Pre-unary operators ++expression, --expression Left-to-right
Other unary operators -, !, ~, +, (type) Right-to-left
Cast (Type)reference Right-to-left
Multiplication/division/modulus *, /, % Left-to-right
Addition/subtraction +, - Left-to-right
Shift operators <<, >>, >>> Left-to-right
Relational operators <, >, <=, >=, instanceof Left-to-right
Equal to/not equal to ==, != Left-to-right
Logical AND & Left-to-right
Logical exclusive OR ^ Left-to-right
Logical inclusive OR | Left-to-right
Conditional AND && Left-to-right
Conditional OR || Left-to-right
Ternary operators boolean expression ? expression1 : expression2 Right-to-left
Assignment operators =, +=, -=, *=, /=, %=, &=, ^=, |=, <<=, >>=, >>>= Right-to-left
Arrow operator -> Right-to-left

We recommend keeping Table 2.1 handy throughout this chapter. For the exam, you need to memorize the order of precedence in this table. Note that you won't be tested on some operators, like the shift operators, although we recommend that you be aware of their existence.

The arrow operator (->), sometimes called the arrow function or lambda operator, is a binary operator that represents a relationship between two operands. Although we won't cover the arrow operator in this chapter, you will see it used in switch expressions in Chapter 3, “Making Decisions,” and in lambda expressions starting in Chapter 8, “Lambdas and Functional Interfaces.”

OCP Oracle Certified Professional Java SE 17 Developer Study Guide

Подняться наверх