Operators – 1Z0-829 Study Guide

OCP EXAM OBJECTIVES COVERED IN THIS CHAPTER:

✓✓ Handling date, time, text, numeric and boolean values

  • Use primitives and wrapper classes including Math API,

parentheses,­ type promotion, and casting to evaluate arithmetic and boolean expressions

The previous chapter talked a lot about defining variables, but what can you do with a variable once it is created? This chapter introduces operators and shows how you can use them to combine existing variables and create new values. It shows you how to apply operators to various primitive data types, including introducing you to operators that can be applied to objects.

Understanding Java Operators

Before we get into the fun stuff, let’s cover a bit of terminology. A Java operator is a special symbol that can be applied to a set of variables, values, or literals—­referred to as operands—­ and that returns a result. The term operand, which we use throughout this chapter, refers

to the value or variable the operator is being applied to. Figure 2.1 shows the anatomy of a Java operation.

FIGURE 2 . 1   Java operation

The output of the operation is simply referred to as the result. Figure 2.1 actually con-tains a second operation, with the assignment operator (=) being used to store the result in variable c.

We’re sure you have been using the addition (+) and subtraction (-­) operators since you were a little kid. Java supports many other operators that you need to know for the exam. While many should be review for you, some (such as the compound assignment operators) may be new to you.

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 fol-lowing 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 prob-lems like this should be second nature.