Chapter 7

Math Operators


CONTENTS

In Chapter 5 "Constants and Variables," you got a quick look at a few math operators, including the times (*), plus (+), and minus (-) signs. You even got a chance to use these operators in a few simple mathematical formulas. There's still a lot more to learn about math operators, though, as you'll discover as you read this chapter. Here, you'll not only learn a few more operators, but also learn about operator precedence, which determines the order in which operations are performed.

The Addition Operator

In case you were sleeping during second grade, you might like to know that the addition operator (+) is used to compute the sum of two values. As with all mathematical operations, Java performs these summing tasks just as you did in your second-grade homework. For example, the following line shows the general form of an addition operation in Java:


result = expr1 + expr2;

Here, the values represented by expr1 and expr2 are added together (summed), with the result being assigned to the variable represented by result. The values expr1 and expr2 are actually expressions, which means that they can be anything from a literal number like 5 to a complex formula like 5*(3+7)^10. You'll get a closer look at expressions in the next chapter, "Expressions."

Example: Using the Addition Operator

Suppose you want to sum the values of two variables. For example, you're writing a program that asks the user for two values and then prints the sum of the values. Assuming that the user's values get stored in two variables called value1 and value2, you might write a line of Java code that looks like this:


sum = value1 + value2;

In this example, if the user entered 12 as the value for value1 and 15 as the value for value2, after Java executed the line, sum would be equal to 27.

Example: Multiple Additions

In the previous example, you saw the simplest way you can use the addition operator. However, you are not limited to adding only two values. You can, in fact, add as many expressions as you like. To extend the previous example, suppose you have four values you need to sum. You can use a line of code like this:


sum = value1 + value2 + value3 + value4;

As you'll see in Chapter 8 "Expressions," you can create all kinds of complicated mathematical formulas with Java.

The Subtraction Operator

You can use the subtraction operator, which looks like a minus sign (-), to subtract one value or expression from another. Although the subtraction operator yields a different result than the addition operator (thank heavens for that), it's used in exactly the same way, as you can see by this general example:


result = expr1 - expr2;

Here, the value represented by expr2 is subtracted from expr1, with the result being assigned to the variable result. Just as you learned with the addition operator, the values expr1 and expr2 are expressions that can be anything that results in a numerical value.

Example: Using the Subtraction Operator

Suppose you want to subtract the value of one variable from another. For example, the program you're writing requires that you subtract a customer's monthly payment from the balance he owes. You might write a line of Java code that looks like this:


new_balance = current_balance - payment;

In this example, if the customer's current balance was $110 and he paid $25, after Java executed the line, new_balance would be equal to $85. (Of course, the subtraction is being done with the numbers 110 and 25, and the result is 85. The computer doesn't know anything about dollars, a fact that makes it tough for a computer to do its grocery shopping.)

NOTE
Although the examples you've seen so far use integers, you can use mathematical operators with any type of numerical value, including floating-point.

Example: Multiple Subtractions Using Mixed Data Types

You know from your experience with the addition operator that you can use more than one mathematical operator in a calculation. The same is true with the subtraction operator. You can also use different types of values in the calculation. For example, suppose you needed to subtract both an integer and a floating-point value from another integer. You could perform this task with a calculation like this:


difference = 100 - 15 - 3.5f;

After Java executes the above line, the variable difference will be equal to 81.5. But do you see a potential problem? What type of value is 81.5? If you said "floating point," go to the head of the class. Because 81.5 is a floating-point value, difference must be a floating-point variable. If difference is an integer, Java's compiler will generate an error that tells you "Explicit cast needed to convert float to int." What Java is really saying here is, "If you want to have an integer result, you've got to tell me." In the next example, you see how to tell Java this important information.

Example: Casting a Result to a Different Data Type

When you cast a value, you're telling Java that it's okay to convert one type of value to another. You do this by placing in front of the calculation, in parentheses, the data type you want. For example, look at this line of Java code:


difference = 100 - 15 - 3.5f;

Because the calculation on the right side of the equals sign results in a floating-point number, difference must be a floating-point variable. After all, computers are very fussy. They refuse to do things like try to stuff a floating-point number into an integer. If difference is an integer, then the result of the calculation must also be an integer. In the above case, you can satisfy Java's compiler by using a type cast, which looks like this:


difference = (int)(100 - 15 - 3.5f);

Now, when Java executes the above line, it first calculates the result of 100-15-3.5f, which is 81.5. Then, it converts the result to an integer by dropping the decimal portion of the value. This gives a result of 81. Finally, Java assigns the value of 81 to difference, which is an integer variable. In short, when you use a type cast, you're telling the compiler, "Yes, I know what I'm doing. I want the result converted."

NOTE
Sometimes the minus sign is used as a negation operator, rather than a subtraction operator. For example, if you want to write a negative number, like negative ten, you'd use the negation operator like this: -10. This is a case where the same symbol is used to mean different things. Java can tell the difference between the negation and a subtraction operators by the context in which the operator is used.

The Multiplication Operator

By now, you should be getting used to using mathematical operations in simple expressions. The multiplication operator (*) is no different from the addition and subtraction operators, except that it performs a different type of operation. When you want to multiply two numbers together, you use the multiplication operator like this:


result = expr1 * expr2;

After Java executes this line, result contains the product of expr1 times expr2. The most important thing to remember about multiplication is that you can run into some pretty big numbers fast. If the result of a multiplication is larger than the data type of the variable that'll hold the answer, you've got trouble, as you'll see in the following example.

Example: Multiplication and Data Types

Try to determine the result of the following calculation:


byte product = (byte)(20 * 20);

If you said the answer is 400, you'd be both right and wrong. While it is true that 20 times 20 is 400, product is only a byte variable, which means it can only hold values from -128 to 127. Unfortunately, Java just goes ahead and stuffs the answer into product whether it fits or not. (The byte type-cast, in fact, converts the answer to a byte before it's stuffed into product, but that's a minor complication.) In the preceding case, you'd end up with an answer of -112.

Be especially careful when you're performing more than one multiplication in a calculation. In such cases, numbers can really get out of hand if you're using the smaller data types like byte or short. Most Java programmers use the int data type for their integer variables, which ensures that their variables have plenty of room for large numbers.

Of course, as I've said before, you should choose the smallest data type that is large enough for the values you'll be using, since the computer must work harder, and thus slower, when it uses larger data types. Still, if you're not performing tons of calculations, using larger data types for safety sake probably won't make a noticeable change in the speed of your applet.

TIP
When a mathematical calculation gives you an answer that seems way out of whack, check to make sure that you're using data types that are large enough to hold the values used in the calculation. This is especially true for the result of the calculation. Many hard-to-find program bugs result from using the wrong data types for large values.

The Division Operator

As you may have guessed, the next operator on the list is the division operator (/), which enables you to divide one value by another. The division operator is used exactly like the other operators you've studied so far, as you can see by this line:


result = expr1 / expr2;

Here, result ends up as the result of expr1 divided by expr2. As with multiplication, there's a trap lurking here, but this time it doesn't have as much to do with the size of the numbers as it does in the division operation itself. The problem is that almost all division calculations end up with floating-point values as answers. The following example demonstrates this potential problem.

Example: Integer Versus Floating-Point Division

Look at this calculation:


int result = 3 / 2;

When you divide 3 by 2, you may start out with integers, but you end up with 1.5 for an answer, and 1.5 is, of course, a floating-point number. But when Java performs the division shown above, it performs integer division. That is, it drops any decimal portion in the answer, leaving result equal to 1. There are times when this is the type of division you want to perform. But if you want the precise answer to 3 / 2, you're going to have to change something. Maybe changing result to a floating-point variable will make a difference:


float result = 3 / 2;

When Java performs this calculation, you still end up with 1 as the answer. Why? Because, as I mentioned before, Java performs integer division on integer values like 3 and 2. To solve the problem, you must also convert 3 and 2 to floating-point values, like this:


float result = 3f / 2f;

Now, you'll get the correct result of 1.5. Actually, only one of the numbers to the right of the equals sign needs to be floating-point in order to get a floating-point answer. This line will work, too:


float result = 3f / 2;

The Modulo Operator

In the previous section, you learned that integer division gives you a result that's equal to the number of times one number fits into another, regardless of the remainder. For example, you now know that, in Java, the answer to "3 divided by 2" is 1, meaning that 2 fits into 3 only once. Integer division throws away the remainder, but what if it's the remainder you're looking for? Then, you can use the modulo operator (%) like this:


result = expr1 % expr2;

This line results in the remainder of expr1 divided by expr2. For example, the calculation


int result = 11 % 3;

makes result equal to 2, because 3 goes into 11 three times with a remainder of 2. You probably won't use the modulo operator much, but it can be handy for special types of calculations.

The Increment Operator

Many times in a program, you want to increase a value by a specific amount. For example, if you were using the variable count to keep track of how many times a part of your program executed, you need to add 1 to count each time you reached that part of the program. Programmers used to do this kind of incrementing like this:


count = count + 1;

Here, the computer takes the value stored in count, increases it by 1, and then assigns the new value to count. If you've ever programmed in C or C++, you know that those languages have a shortcut way of incrementing a value. Because Java is much like C++, its creators also included this shortcut operator. Using the increment operator (++), you can replace the previous line with this one:


++count;

Another way to write the preceding line is like this:


count++;

There is, however, a subtle difference in the way the increment operator works when it's placed before (pre-increment) or after (post-increment) the value it's incrementing. The difference crops up when you use the operator in expressions. For example, look at these lines of Java program code:


int num1 = 1;

int num2 = ++num1;

Here, Java first sets the variable num1 to 1. In the second line, Java increments num1 to 2 and then assigns 2 to num2.

Now, look at these lines:


int num1 = 1;

int num2 = num1++;

This time, num2 ends up as 1. Why? In the second line, Java doesn't increment num1 until after it assigns the current value of num1 (1) to num2. Watch out for this little detail when you get started writing your own applets.

What if you want to increment a value by more than 1? The old-fashioned way would be to use a line like this:


num = num + 5;

Java has a special shortcut operator that handles the above situation, too. You use the shortcut operator like this:


num += 5;

The above line just says, "Add 5 to num."

The Decrement Operator

In computer programs, you don't always count forwards. Often, you need to count backwards as well. That's why Java has the decrement operator (- -), which works just like the increment operator, except it subtracts 1 instead of adding it. You use the decrement operator like this:


- -num;

The above example uses the pre-decrement version of the operator. If you want to decrement the value after it's been used in an expression, use the post-decrement version, like this:


num- -;

The set of operators wouldn't be complete without a decrement operator that enables you to subtract any value from a variable. The following line


num -= 5;

tells Java to decrement num by 5.

Example: Using Mathematical Calculations in an Applet

It's one thing to learn about mathematical operators and how they're used to perform calculations. It's quite another to actually use these operators in an actual program. This is because, when performing calculations in programs, you frequently have to do a lot of conversions from numerical values to strings and vice versa. For example, suppose you ask the user for a number that you need in order to perform a calculation. When you retrieve the number from the user, it's still in string form. You can't use the text character "3" in a calculation. You need to convert the string form of "3" to the numerical form.

Once you have all your values converted to the right form, you can go ahead and do the calculations as you learned in this chapter. But what about when you want to show the answers to your applet's user? Again, you need to perform a conversion, this time from numerical form back to string form. Listing 7.1 shows an applet called Applet5 that demonstrates how these conversion tasks work. Figure 7.1 shows Applet5 running in the Appletviewer application.

Figure 7.1 : The Applet5 applet sums two values.


Listing 7.1  Applet5.java: Source Code for the Applet5 Applet.

import java.awt.*;

import java.applet.*;



public class Applet5 extends Applet

{

    TextField textField1;

    TextField textField2;



    public void init()

    {

        textField1 = new TextField(5);

        textField2 = new TextField(5);

        add(textField1);

        add(textField2);

        textField1.setText("0");

        textField2.setText("0");

   

 }



    public void paint(Graphics g)

{

        int value1;

        int value2;

        int sum;



        g.drawString("Type a number in each box.", 40, 50);

        g.drawString("The sum of the values is:", 40, 75);

        String s = textField1.getText();

        value1 = Integer.parseInt(s);

        s = textField2.getText();

        value2 = Integer.parseInt(s);

        sum = value1 + value2;

        s = String.valueOf(sum);

        g.drawString(s, 80, 100);

    }



    public boolean action(Event event, Object arg)

    {

        repaint();

        return true;

    }

}


Tell Java that the program uses classes in the awt package.
Tell Java that the program uses classes in the applet package.
Derive the Applet5 class from Java's Applet class.
Declare TextField objects called textField1 and textField2.
Override the Applet class's init() method.
Create the two TextField objects.
Add the two TextField objects to the applet.
Initialize the text in both TextField objects to "0".
Override the Applet class's paint() method.
Declare three integers called value1,value2, and sum.
Display two text strings in the applet's display area.
Get the text from first TextField object.
Convert the text to an integer.
Get the text from the second TextField object.
Convert the text to an integer.
Add the two converted values together.
Convert the sum to a string.
Draw the text string on the applet's surface.
Override the Applet class's action() method.
Tell Java to redraw the applet's display area.
Tell Java that the action() method finished successfully.

Use the procedures you learned in the previous chapter to compile and run the Applet5 applet. Remember that to do this, you must follow these steps:

  1. Type and save the program (or copy it from the CD-ROM).
  2. Compile the applet.
  3. Write an HTML document to test the applet.
  4. Use Appletviewer to display the HTML document containing the applet.

When you have the Applet5 applet up and running, enter a number into each text box, and then press Enter. When you do, the applet sums the two numbers and displays the result.

How Applet5 Works

Although Applet5's source code is a little longer than other applets you've seen, it's really not much more complicated. It simply uses a few more variables in order to store the values needed to perform its calculations.

First, near the top of the program, Applet5 declares two TextField objects, like this:


TextField textField1;

TextField textField2;

These TextField objects represent the text boxes in which the user types the values to be summed.

Next, the program overrides the Applet class's init() method. In this method, it first creates two new TextField objects:


textField1 = new TextField(5);

textField2 = new TextField(5);

The program then adds the TextField objects to the applet:


add(textField1);

add(textField2);

Finally, in order to be sure the program doesn't try to sum two non-existent values, init() initializes the text contained in the TextField objects to "0":


textField1.setText("0");

textField2.setText("0");

The TextField class's setText() method sets the text contained in the control to the text string given as the method's single argument.

NOTE
Overriding a method is the process of replacing a method found in the base class with a version specific to the new class. In other words, the Applet class from which Applet5 is derived also has an init() method. If you didn't override init() in Applet5, Java would call the original version in Applet instead. (See the example called "Encapsulation, Inheritance, and Polymorphism" in Chapter 4for more information.)

The paint() method is where all the action takes place. In paint(), the program first declares three integer variables:


int value1;

int value2;

int sum;

NOTE
Because it takes a certain amount of time for a computer to allocate memory for variables, it's not always a good idea to declare variables inside the paint() method, which must run as quickly as possible. I chose to use this generally frowned upon practice in order to keep the programming examples simple and easy-to-understand. However, keep in mind that the paint() method must do as little processing as possible in order to keep it up to speed.

After declaring its variables, paint() displays two lines of text on the applet's display area:


g.drawString("Type a number in each box.", 40, 50);

g.drawString("The sum of the values is:", 40, 75);

Then, the program extracts the text from the first TextField object and converts that text from a string to a numerical value (in this case, an integer):


String s = textField1.getText();

value1 = Integer.parseInt(s);

You've seen the TextField class's getText() method before. The second line above, however, introduces you to a new class and method. The Integer class offers many methods that make working with integers easier. For example, the parseInt() method used in the second line above enables you to convert the contents of a string to an integer (assuming, of course, that the string contains numerical digits).

After converting the first string to an integer, paint() handles the second TextField object in exactly the same way:


s = textField2.getText();

value2 = Integer.parseInt(s);

Now the program has two integer values, stored in the variables value1 and value2, that it can sum, which it does like this:


sum = value1 + value2;

After Java executes the above lines, the answer to the calculation is stored in sum. The program now needs to display the answer to the applet's user. However, before it can do that, it must convert the numerical value in sum to a text string that can be displayed on the screen. You know that the String class's valueOf() method handles this task. The last thing paint() does, then, is convert sum to a string and display the string on the screen:


s = String.valueOf(sum);

g.drawString(s, 80, 100);

The last method in Applet3 is action(), which you learned about in the previous chapter. To review, Java calls action() whenever the user performs some action with the applet's controls. In this case, action() responds when the user presses Enter in one of the TextField objects.

The Order of Operations

Now that you know how to use mathematical operators, you need to know about the complications you can run into when you use different operators in the same calculation. The order of operations, which is also called operator precedence, determines the order in which mathematical computations are performed. If you've ever taken algebra, you know that mathematicians long ago set up a standard set of symbols for mathematical operations as well as defined the order in which they're performed. These mathematical rules are also observed in programming languages like Java. Table 7.1 lists Java's mathematical operators in order of precedence.

Table 7.1  Operator Order of Operations.

Operator
Description
-
Negation
++
Increment
- -
Decrement
*
Multiplication
/
Division
%
Modulus
+
Addition
-
Subtraction
=
Assignment

As I mentioned previously, operator precedence comes into play when you use several different operators in the same calculation. For example, look at this line of Java source code:


answer = 3 + 5 * 3;

Go ahead and do the calculation. What did you get for an answer? If you got 18, you already know how operator precedence works. If you're new to this sort of thing, you probably got 24 for an answer, which is incorrect. The reason 18 is the correct answer is because operator precedence dictates that the multiplication be performed before the addition. If you look at Table 7.1, you can see that multiplication comes before addition.

If you really wanted to get 24 for an answer, you could use parentheses to change the order of operations, like this:


answer = (3 + 5) * 3;

Now, the answer would be 24, because the parentheses tell Java to do the addition first.

Example: Order of Operations

If you've never dealt with order of operations before, you'll probably need a little practice to get the hang of it. Look at this calculation:


answer = 5 + 3 - 2 + 7;

You should get 13 for an answer. Because addition and subtraction have the same order of precedence in this calculation (yes, I know the table lists subtraction after addition, but if you do the subtraction first, you'll still get 13 for an answer), you can just work from left to right to solve this problem.

Example: More Order of Operations

The previous example was pretty easy. Ready to try something a little tougher? Look at this calculation:


answer = 4 * 5 + 4 / 2;

What do you get for an answer? You should have gotten 22. If you got 12, you forgot that multiplication and division are performed before addition.

Example: Still More Order of Operations

Suppose I change the previous example to this:


answer = 4 * (5 + 4) / 2;

You should get 18 for an answer, because the added parentheses tell you to perform the addition first.

Example: One Last Order of Operations

Okay, now you're going to get a chance to prove that you really know your stuff. Solve this calculation:


answer = 2 * 3 + 6 * 3 - (4 + 2) * 2;

The answer is 12. You solve the problem as shown below:

answer = 2 * 3 + 6 * 3 - (4 + 2) * 2;
answer = 2 * 3 + 6 * 3 - 6 * 2;
answer = 6 + 6 * 3 - 6 * 2;
answer = 6 + 18 - 6 * 2;
answer = 6 + 18 - 12;
answer = 12;

Summary

Almost all computer programs perform mathematical calculations. So that you can specify the types of calculations you want performed, computer languages such as Java feature mathematical operators for standard operations such as addition, subtraction, multiplication, and division. However, when using these operators, always remember operator precedence (or order of operations), which determines the order in which calculations are completed.

Review Questions

  1. What symbols does Java use for the addition, subtraction, multiplication, and division operators?
  2. What does 5*3 equal?
  3. What is the answer to 3 - 2 + 5 + 6 - 1?
  4. If num equals 12, what does the expression ++num do?
  5. What result do you get from 12 % 5?
  6. If num equals 25, what does the expression num += 5 do?
  7. How do you set the text in a TextField object?
  8. What is the answer to 12 + 3 * 6 / 2?
  9. How do you change the calculation 3 / 5 so that is uses floating-point division?
  10. How do you use casting to change the result of 56 - 34.56f from floating point to integer?
  11. How do you convert digits in a string to an integer value?
  12. What is the answer to (12 - 8) * 10 / 2 * 2?

Review Exercises

  1. On a piece of paper, write an expression that sums five numbers.
  2. Write an expression that uses both addition and multiplication with four numbers.
  3. Use parentheses to change the order of operations in the expression you wrote in the previous exercise.
  4. Modify Applet5 so that it accepts three values from the user. Divide the second value by the third and then add the first value. Rename the program MathApplet.java. Figure 7.2 shows what the final applet should look like. (You can find the solution to this programming problem in the CHAP07 folder of this book's CD-ROM.)
    Figure 7.2 : MathApplet should look like this.