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

Arithmetic Operators

Оглавление

Arithmetic operators are those that operate on numeric values. They are shown in Table 2.4.

TABLE 2.4 Binary arithmetic operators

Operator Example Description
Addition a + b Adds two numeric values
Subtraction c - d Subtracts two numeric values
Multiplication e * f Multiplies two numeric values
Division g / h Divides one numeric value by another
Modulus i % j Returns the remainder after division of one numeric value by another

You should know all but modulus from early mathematics. If you don't know what modulus is, though, don't worry—we'll cover that shortly. Arithmetic operators also include the unary operators, ++ and --, which we covered already. As you may have noticed in Table 2.1, the multiplicative operators (*, /, %) have a higher order of precedence than the additive operators (+, -). Take a look at the following expression:

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

First, you evaluate the 2 * 5 and 3 * 4, which reduces the expression to this:

int price = 10 + 12 - 8;

Then, you evaluate the remaining terms in left-to-right order, resulting in a value of price of 14. Make sure you understand why the result is 14 because you will likely see this kind of operator precedence question on the exam.

All of the arithmetic operators may be applied to any Java primitives, with the exception of boolean. Furthermore, only the addition operators + and += may be applied to String values, which results in String concatenation. You will learn more about these operators and how they apply to String values in Chapter 4, “Core APIs.”

OCP Oracle Certified Professional Java SE 17 Developer Study Guide

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