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

Changing the Order of Operation

Оглавление

Let's return to the previous price example. The following code snippet contains the same values and operators, in the same order, but with two sets of parentheses added:

int price = 2 * ((5 + 3) * 4 - 8);

This time you would evaluate the addition operator 5 + 3, which reduces the expression to the following:

int price = 2 * (8 * 4 - 8);

You can further reduce this expression by multiplying the first two values within the parentheses:

int price = 2 * (32 - 8);

Next, you subtract the values within the parentheses before applying terms outside the parentheses:

int price = 2 * 24;

Finally, you would multiply the result by 2, resulting in a value of 48 for price.

Parentheses can appear in nearly any question on the exam involving numeric values, so make sure you understand how they are changing the order of operation when you see them.

When you encounter code in your professional career in which you are not sure about the order of operation, feel free to add optional parentheses. While often not required, they can improve readability, especially as you'll see with ternary operators.

OCP Oracle Certified Professional Java SE 17 Developer Study Guide

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