# Operators¶

Java uses the standard mathematical operators for addition (+), subtraction (-), multiplication (*), and division (/). Java uses (==) to test if the value on the left is equal to the value on the right and (!=) to test if two items are not equal. But, the percent sign operator (%) is the modulus or remainder operator.

Try the following in DrJava’s interaction pane. You can download DrJava for free from http://www.drjava.org. The interaction pane lets you try out Java code without having to declare a class. It also automatically prints the result of a statement when you press enter. What does it print when you type each of the following lines and hit enter?

11 % 10
3 % 4
8 % 2
9 % 2


The modulus operator (%) returns the remainder after you divide the first number by the second number. The modulus operator has been used quite a bit on the AP CS A exam, so you should be familiar with it.

• Use it to check for odd or even numbers (num % 2 == 1 is odd and num % 2 == 0 is even). Actually, you can use it to check if any number is evenly divisible by another (num1 % num2 == 0)
• Use it to get the last digit from an integer number (num % 10 = last digit on right). This approach could be used on the free response question Self Divisor (Question 1 from 2007). See http://coweb.cc.gatech.edu/ice-gt/1277 for starter code and testing code.
• Use it to get the number of minutes left when you convert to hours (num % 60). Also whenever you have limited storage and you need to wrap around to the front if the value goes over the limit. See question 3 at http://coweb.cc.gatech.edu/ice-gt/1278.
3-4-1: What is the result of 158 % 10?

3-4-2: What is the result of 3 % 8?

You are also expected to know the double plus operator (++) and the double minus operator (--). The ++ operator is used to add one to the current value: x++ is the same as x = x + 1. The -- operator is used to subtract one from the current value: y-- is the same as y = y - 1. You should know that x += y is the same as x = x + y, x -= y is the same as x = x - y, x *= y is the same as x = x * y, and x /= y is the same as x = x / y.

3-4-3: What are the values of x, y, and z after the following code executes?

int x = 0;
int y = 1;
int z = 2;
x--; // x followed bythe double minus sign
y++;
z+=y;