Читать книгу OCP Oracle Certified Professional Java SE 17 Developer Study Guide - Jeanne Boyarsky - Страница 131
Types of Operators
ОглавлениеJava supports three flavors of operators: unary, binary, and ternary. These types of operators can be applied to one, two, or three operands, respectively. For the exam, you need to know a specific subset of Java operators, how to apply them, and the order in which they should be applied.
Java operators are not necessarily evaluated from left-to-right order. In this following example, the second expression is actually evaluated from right to left, given the specific operators involved:
int cookies = 4; double reward = 3 + 2 * --cookies; System.out.print("Zoo animal receives: "+reward+" reward points");
In this example, you first decrement cookies
to 3
, then multiply the resulting value by 2
, and finally add 3
. The value then is automatically promoted from 9
to 9.0
and assigned to reward
. The final values of reward
and cookies
are 9.0
and 3
, respectively, with the following printed:
Zoo animal receives: 9.0 reward points
If you didn't follow that evaluation, don't worry. By the end of this chapter, solving problems like this should be second nature.