chapter 9b — expressions and arithmetic operators

25
Source URL: http://chortle.ccsu.edu/java5/Notes/chap09B/ch09B_1.html Saylor URL: http://www.saylor.org/courses/cs101/#3.3 © Bradley Kjell Saylor.org Used by permission. Page 1 of 25 “Chapter 9B: Expressions and Arithmetic Operators” Bradley Kjell (Revised 02/11/07) CHAPTER 9B — Expressions and Arithmetic Operators This chapter continues the discussion of arithmetic expressions, integer operators, and floating point operators. Chapter Topics: Review of Expressions Arithmetic Operators Integer operators Floating point operators Mixed Floating point and Integer Expressions Constants QUESTION 1: (Review: ) Is the following correct? 13 * 6 -

Upload: others

Post on 18-Dec-2021

15 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: CHAPTER 9B — Expressions and Arithmetic Operators

 Source  URL:  http://chortle.ccsu.edu/java5/Notes/chap09B/ch09B_1.html  Saylor  URL:  http://www.saylor.org/courses/cs101/#3.3  ©  Bradley  Kjell     Saylor.org  Used  by  permission.     Page  1  of  25  

“Chapter 9B: Expressions and Arithmetic Operators” Bradley Kjell (Revised 02/11/07)

CHAPTER 9B — Expressions and Arithmetic Operators

This chapter continues the discussion of arithmetic expressions, integer operators, and floating point operators. Chapter Topics: ▪ Review of Expressions ▪ Arithmetic Operators ▪ Integer operators ▪ Floating point operators ▪ Mixed Floating point and Integer Expressions ▪ Constants QUESTION 1: (Review: ) Is the following correct? 13 * 6 -

Page 2: CHAPTER 9B — Expressions and Arithmetic Operators

 Source  URL:  http://chortle.ccsu.edu/java5/Notes/chap09B/ch09B_1.html  Saylor  URL:  http://www.saylor.org/courses/cs101/#3.3  ©  Bradley  Kjell     Saylor.org  Used  by  permission.     Page  2  of  25  

Answer: No.

Expressions

The literals (the integers) and the operators are out of order in the above incorrect expression. (One legal arrangement is 13 * -6 for 13 times minus 6.) An expression is a combination of literals, operators, variable names, and parentheses used to calculate a value. Expressions contain operators and operands. You already know what an operator is (a symbol such as +, -, *, or / that calls for an arithmetic operation). An operand is a value that is acted upon by an operator. The parts of an expression must be arranged correctly. The syntax of Java describes the correct arrangements. The rules for correct Java expressions are about the same as for algebra. Essentially, ▪ Each operator must have the correct number of operands. Multiplication *, Division /, Addition +, Subtraction - should have two

operands, one on each side. Negation - and unary plus + should be followed by one operand. ▪ Parentheses () can surround a legal expression to make it an operand. In Java expressions, operators and operands must be explicit. In 13 - 5 the 13 and the 5 are the operands and the - is the operator. In 14*sum 14 and sum are the operands. The star for multiplication must be present. The expression 14sum is incorrect. The details of expression syntax are in the Java documentation, should you care to dig through it. The best way to learn these rules is to study some examples. QUESTION 2: Which minus sign in the following stands for "subtraction" and which stands for "negation"? -23 – 3

Page 3: CHAPTER 9B — Expressions and Arithmetic Operators

 Source  URL:  http://chortle.ccsu.edu/java5/Notes/chap09B/ch09B_1.html  Saylor  URL:  http://www.saylor.org/courses/cs101/#3.3  ©  Bradley  Kjell     Saylor.org  Used  by  permission.     Page  3  of  25  

Answer: -23 - 3

The first minus sign is "negation" and the second minus sign is "subtraction". The spaces in the expression emphasize the different roles, but are not necessary. The following expression is equivalent: -23-3

Practice

Examine the following expressions. Assume that each variable has already been correctly declared. Decide if the expression is correct, then click on the button.

     

Page 4: CHAPTER 9B — Expressions and Arithmetic Operators

 Source  URL:  http://chortle.ccsu.edu/java5/Notes/chap09B/ch09B_1.html  Saylor  URL:  http://www.saylor.org/courses/cs101/#3.3  ©  Bradley  Kjell     Saylor.org  Used  by  permission.     Page  4  of  25  

Expression Correct or Not Correct? Expression Corrector Not

Correct?

25

CORRECT. The expression is correct. A

single integer literal is an expression.

25 - value CORRECT.

2( a - b )

NOT CORRECT. The 2 must have an operator

between it and the second operand.

(a-b) * (c-d) CORRECT.

A - b/c + D CORRECT. -sum + partial

CORRECT. The first - is a unary minus that makes

sum negative.

( (x+y) / z ) / ( a - b )

CORRECT. The parentheses ARE balanced.

( (m - n) + (w-x-z) / (p % q )

NOT CORRECT. The

parentheses are NOT balanced.

 QUESTION 3: Are arithmetic expressions the only kind of expression?

Page 5: CHAPTER 9B — Expressions and Arithmetic Operators

 Source  URL:  http://chortle.ccsu.edu/java5/Notes/chap09B/ch09B_1.html  Saylor  URL:  http://www.saylor.org/courses/cs101/#3.3  ©  Bradley  Kjell     Saylor.org  Used  by  permission.     Page  5  of  25  

Answer: No. For example, the following is also an expression: "This is" + " a string" + " expression"

The above expression creates a new string that is the concatenation of all the strings.

Arithmetic Operators

Operator Meaning precedence

- unary minus highest

+ unary plus highest

* multiplication middle

/ division middle

% remainder middle

+ addition low

- subtraction low

But arithmetic expressions are especially important. As you have seen, Java has many operators for arithmetic: All of these operators can be used on floating point numbers and on integer numbers. (However, the % operator is rarely used on floating point.) For instance, / means integer division if both operands are integers, and means floating point division if one or both operands are floating point. An integer operation is always done with 32 bits or more. If one or both operand is 64 bits (data type long) then the operation is done with 64 bits. Otherwise the operation is done with 32 bits, even if both operands are smaller than 32 bits. For example, with 16 bit short variables, the arithmetic is done using 32 bits: short x = 12; // 16 bit short

int result; // 32 bit int

result = x / 3; // arithmetic will be

// done using 32 bits

The expression x / 3 divides a 32-bit 12 by a 32-bit 3 and puts the 32-bit answer in result. The literal 3 automatically represents a 32-bit value. QUESTION 4: Does it really matter that 12 was converted to 32 bits?

Page 6: CHAPTER 9B — Expressions and Arithmetic Operators

 Source  URL:  http://chortle.ccsu.edu/java5/Notes/chap09B/ch09B_1.html  Saylor  URL:  http://www.saylor.org/courses/cs101/#3.3  ©  Bradley  Kjell     Saylor.org  Used  by  permission.     Page  6  of  25  

Answer: Not in this example. But sometimes it does, when values are close to the limit of what can be represented in 16 bits.

Another Example Here is another example: short x = 12;

short y = 3;

short value;

value = x / y;

The expression x / y divides a 32-bit 12 by a 32-bit 3, even though the variables x and y are only 16 bits wide. The calculation produces a 32-bit result. Because the 32-bit result does not fit in the 16 bits of value the compiler will not compile the last statement. This can be completely baffling when it happens to you.

   For professional programmers, details like these are sometimes important. But for most programs, just use int or long for integers and double for floating point. This will keep you out of trouble (usually). If you can't avoid the problem, use a type cast, as described in chapter 28. QUESTION 5: Do you expect that a modern electronic calculator will give you the same answer as Java for the expression (31.5 - 12)/4.1 ?

Page 7: CHAPTER 9B — Expressions and Arithmetic Operators

 Source  URL:  http://chortle.ccsu.edu/java5/Notes/chap09B/ch09B_1.html  Saylor  URL:  http://www.saylor.org/courses/cs101/#3.3  ©  Bradley  Kjell     Saylor.org  Used  by  permission.     Page  7  of  25  

Answer: Yes. The meaning of operators and parentheses is about the same in electronic calculators and in Java. But Java does integer and floating point math, and sometimes this can make a difference.

Weird Integer Arithmetic The division operator / means integer division if there is an integer on both sides of it. If one or two sides has a floating point number, then it means floating point division. The result of integer division is always an integer. Integer division determines how many times one number goes into another. The remainder after integer division is simply dropped, no matter how big it is. There is a difference between what Java will do and what a calculator will do. A calculator will do floating point arithmetic for the expression: 7/4

A calculator will show this as 1.75. Java will regard this as integer arithmetic and give you: 7/4 = 1

because 4 goes into 7 just once. The result is not rounded up to 2. The remainder after division, 3, is simply dropped. QUESTION 6: What is the result of evaluating the following expression: 199/50

Page 8: CHAPTER 9B — Expressions and Arithmetic Operators

 Source  URL:  http://chortle.ccsu.edu/java5/Notes/chap09B/ch09B_1.html  Saylor  URL:  http://www.saylor.org/courses/cs101/#3.3  ©  Bradley  Kjell     Saylor.org  Used  by  permission.     Page  8  of  25  

Answer: 199/50 = 3

50 goes into 199 three times and the remainder, 49, is dropped.

Mixed Integer and Float Integer division is easy enough to see when it is by itself, but here is a more confusing case of the same thing: 1.5 + 7/2

The division is done first, because / has higher precedence than +. The result, 3, is an integer. Now the floating point 1.5 is added to integer 3 to get floating point 4.5. Integer arithmetic might be used in some parts of an expression and not in others, even though the final value of the expression is floating point. QUESTION 7: What is the result of evaluating the following expression: 1/2 + ½

Page 9: CHAPTER 9B — Expressions and Arithmetic Operators

 Source  URL:  http://chortle.ccsu.edu/java5/Notes/chap09B/ch09B_1.html  Saylor  URL:  http://www.saylor.org/courses/cs101/#3.3  ©  Bradley  Kjell     Saylor.org  Used  by  permission.     Page  9  of  25  

Answer: 1/2 + 1/2 = 0

It looks as though this is a mistake, but no: each 1/2 calls for integer division, resulting in an integer 0. The two zeros are added to get the final answer, zero.

Copy-and-Paste Program

If you really want to add one half to one half you should write 1.0/2.0 + 1.0/2.0 because now the decimal points make each number a double. Here is some Java code that illustrates these points: class IntegerDivision

{

public static void main ( String[] args )

{

System.out.println("The result is: " + (1/2 + 1/2) );

}

}

Copy this program to a file IntegerDivision.java, compile, and run it. See a previous chapter for details on doing this. Make some changes to the program using your text editor then run it to see the effect. Notice the parentheses around (1/2 + 1/2). These are necessary so that the arithmetic is done first, then the result is converted to characters and appended to the string. QUESTION 8: What is the value of the expression 99/100 ?

Page 10: CHAPTER 9B — Expressions and Arithmetic Operators

 Source  URL:  http://chortle.ccsu.edu/java5/Notes/chap09B/ch09B_1.html  Saylor  URL:  http://www.saylor.org/courses/cs101/#3.3  ©  Bradley  Kjell     Saylor.org  Used  by  permission.     Page  10  of  25  

Answer: 99/100 = 0 It is tempting to think that the answer must be 1, but it is not. 100 goes into 99 zero times, so that is the result.

Practice The normal rules of arithmetic are used to determine the sign of the result of division:

It is easiest to first calculate the result as if num and div were positive, then apply the above rules. For example:

Of course, you are eager to practice this right away! Mentally (or with scratch paper) decide on the value of each expression. Then click on the button to see the correct value.

Page 11: CHAPTER 9B — Expressions and Arithmetic Operators

 Source  URL:  http://chortle.ccsu.edu/java5/Notes/chap09B/ch09B_1.html  Saylor  URL:  http://www.saylor.org/courses/cs101/#3.3  ©  Bradley  Kjell     Saylor.org  Used  by  permission.     Page  11  of  25  

QUESTION 9: What is the value of the expression 3/4 ?

Page 12: CHAPTER 9B — Expressions and Arithmetic Operators

 Source  URL:  http://chortle.ccsu.edu/java5/Notes/chap09B/ch09B_1.html  Saylor  URL:  http://www.saylor.org/courses/cs101/#3.3  ©  Bradley  Kjell     Saylor.org  Used  by  permission.     Page  12  of  25  

Answer: 0

Subexpressions The expression 3/4 calls for integer division because both the operands are integers. The expression 3.0/4.0 calls for floating point division because both the operands are floating point. Most of the operators we are interested in take two operands. In each of the following examples the operator has two operands:

However, unary operators take just one operand:

A binary operator will always have exactly two operands. However, sometimes one or both operands of a binary operator is a subexpression. A subexpression is a part of an expression that is by itself a correct expression. Sometimes a subexpression is a constant, like "8". Any expression can be a subexpression of a larger expression. In the following, both operands of the red operator are subexpressions.

QUESTION 10: In an expression like 34.12 / 68.0 how do you know if the / means integer division or means floating point division ?

Page 13: CHAPTER 9B — Expressions and Arithmetic Operators

 Source  URL:  http://chortle.ccsu.edu/java5/Notes/chap09B/ch09B_1.html  Saylor  URL:  http://www.saylor.org/courses/cs101/#3.3  ©  Bradley  Kjell     Saylor.org  Used  by  permission.     Page  13  of  25  

Answer: You look at the operands of the operator.

Mixed Floating Point and Integer Expressions But what if one operand is an integer and the other is a floating point? The rule is: If both operands are integers, then the operation is an integer operation. If any operand is floating point, then the operation is floating point. For example, the following are integer operations (assume that a and b are int variables):

12 * b a - 2 56%a

Each operation in the following expressions is a floating point operation (assume that a and b are int variables, and that x and y are floating point variables):

x * b (a - 2.0) 56*y

In more complicated expressions, an operand of a particular operator might be a subexpression. But the rule still applies: if one or both operand is a floating point type then the operation is floating point. In the following, each / operation is floating point:

(12.0 * 31) / 12 (a - 2.0) / b 56*x/3

In that last example, the 56*x is a floating point subexpression that is one of the operands for the division operator. (Because * and / have equal precedence, so evaluation is done from left to right.) QUESTION 11: What type (integer or floating point) of operator is the / in the following: (12 + 0.0) / 7

Page 14: CHAPTER 9B — Expressions and Arithmetic Operators

 Source  URL:  http://chortle.ccsu.edu/java5/Notes/chap09B/ch09B_1.html  Saylor  URL:  http://www.saylor.org/courses/cs101/#3.3  ©  Bradley  Kjell     Saylor.org  Used  by  permission.     Page  14  of  25  

Answer: Floating point. Adding floating point 0.0 to the integer 12 results in a floating point 12.0. Now the division is floating point because one of its operands is. This is a common programming trick.

Mixed Expression Gotcha! Look again at the rule: If both operands are integers, then the operation is an integer operation. If any operand is floating point, then the operation is floating point. The rule has to be applied step-by-step. Consider this expression: ( 1/2 + 3.5 ) / 2.0

What is the result? Apply the rules: innermost parentheses first, within the parentheses the highest precedence operator first: ( 1/2 + 3.5 ) / 2.0

---

do first

Since both operands are integer, the operation is integer division, resulting in: ( 0 + 3.5 ) / 2.0

Now continue to evaluate the expression inside parentheses. The + operator is floating point because one of its operands is, so the parentheses evaluates to 3.5: 3.5 / 2.0

Finally do the last operation: 1.75

This is close to the result that you might have mistakenly expected if you thought both divisions were floating point. An insidious bug might be lurking in your program! QUESTION 12: Surely you want to try another! What is the result of evaluating this expression: ( a/b + 4) / 2

Assume that a contains 6 and b contains 12.0

Page 15: CHAPTER 9B — Expressions and Arithmetic Operators

 Source  URL:  http://chortle.ccsu.edu/java5/Notes/chap09B/ch09B_1.html  Saylor  URL:  http://www.saylor.org/courses/cs101/#3.3  ©  Bradley  Kjell     Saylor.org  Used  by  permission.     Page  15  of  25  

Answer: (a/b + 4) / 2 == (6/12.0 + 4) / 2 == (0.5 + 4) / 2 == 4.5/2 == 2.25

Fun with Mixed Expressions

Examine each expression in the following list. Decide if the operator in the button is an integer operation or a floating point operation. Then click on the operator to see if you are correct.

Warning: These questions ask if the operator is floating point or integer. The value of the complete expression may be of a different type than one of its operators.

Page 16: CHAPTER 9B — Expressions and Arithmetic Operators

 Source  URL:  http://chortle.ccsu.edu/java5/Notes/chap09B/ch09B_1.html  Saylor  URL:  http://www.saylor.org/courses/cs101/#3.3  ©  Bradley  Kjell     Saylor.org  Used  by  permission.     Page  16  of  25  

QUESTION 13: What is the remainder after dividing 13 by 5 (with integer division)?

Page 17: CHAPTER 9B — Expressions and Arithmetic Operators

 Source  URL:  http://chortle.ccsu.edu/java5/Notes/chap09B/ch09B_1.html  Saylor  URL:  http://www.saylor.org/courses/cs101/#3.3  ©  Bradley  Kjell     Saylor.org  Used  by  permission.     Page  17  of  25  

Answer: 3

Remainder Operator You may recall how in grade school you did division like this:

13 / 5 == 2 with a remainder of 3. This is because 13 == 2*5 + 3. The symbol for finding the remainder is % (percent sign). This symbol is also called the modulo operator. If you look in the table of operators you will see that it has the same precedence as / and *. Here is a program that is worth study:

Copy this program to a file and play with it. Change the 17 and 3 to other numbers and observe the result. QUESTION 14: Why were the innermost set of parentheses used in the statement: System.out.println("The original : " + (quotient*3 + remainder) );

Page 18: CHAPTER 9B — Expressions and Arithmetic Operators

 Source  URL:  http://chortle.ccsu.edu/java5/Notes/chap09B/ch09B_1.html  Saylor  URL:  http://www.saylor.org/courses/cs101/#3.3  ©  Bradley  Kjell     Saylor.org  Used  by  permission.     Page  18  of  25  

Answer: The parentheses force evaluation of the entire arithmetical expression (quotient*3 + remainder). Then the result is converted to characters and appended to the string. Without the parentheses, the subexpressions are evaluated independently, converted to characters, and appended to the string.

Taking an Integer Apart The integer division operator / and the remainder operator % take an integer apart. theInteger / divisor quotient

theInteger % divisor remainder

The original integer can be put back together again: quotient * divisor + remainder theInteger

In many calculations, it is convenient to do everything with integers, so both / and % are needed. QUESTION 15: If you exchange 372 pennies for dollar bills, how many bills do you get? How many pennies are left over?

Page 19: CHAPTER 9B — Expressions and Arithmetic Operators

 Source  URL:  http://chortle.ccsu.edu/java5/Notes/chap09B/ch09B_1.html  Saylor  URL:  http://www.saylor.org/courses/cs101/#3.3  ©  Bradley  Kjell     Saylor.org  Used  by  permission.     Page  19  of  25  

Answer: ▪ Number of dollar bills is 372 / 100 == 3 ▪ Left over pennies is 372 % 100 == 72

Practice with Remainder Operator For positive numbers, INT % X means to fit as many X as you can into INT, and then the left over amount is the value of the expression. Try that with the following:

Page 20: CHAPTER 9B — Expressions and Arithmetic Operators

 Source  URL:  http://chortle.ccsu.edu/java5/Notes/chap09B/ch09B_1.html  Saylor  URL:  http://www.saylor.org/courses/cs101/#3.3  ©  Bradley  Kjell     Saylor.org  Used  by  permission.     Page  20  of  25  

QUESTION 16: If X is odd, what is X%2?

Page 21: CHAPTER 9B — Expressions and Arithmetic Operators

 Source  URL:  http://chortle.ccsu.edu/java5/Notes/chap09B/ch09B_1.html  Saylor  URL:  http://www.saylor.org/courses/cs101/#3.3  ©  Bradley  Kjell     Saylor.org  Used  by  permission.     Page  21  of  25  

Answer: One. This is a common programming trick. Often you need to know the oddness and eveness of an integer.

Remainder with Negative Integers The remainder operator can be used with negative integers. The rule is: ▪ Perform the operation as if both operands were positive. ▪ If the left operand is negative, then make the result negative. ▪ If the left operand is positive, then make the result positive. ▪ Ignore the sign of the right operand in all cases. For example: 17 % 3 == 2 -17 % 3 == -2

17 % -3 == 2 -17 % -3 == -2

You may wish to practice with the following:

Page 22: CHAPTER 9B — Expressions and Arithmetic Operators

 Source  URL:  http://chortle.ccsu.edu/java5/Notes/chap09B/ch09B_1.html  Saylor  URL:  http://www.saylor.org/courses/cs101/#3.3  ©  Bradley  Kjell     Saylor.org  Used  by  permission.     Page  22  of  25  

QUESTION 17: Five pirates find a chest of 123 gold coins and wish to divide the 123 coins evenly amoung themselves. How many coins does each pirate get? The parrot gets any leftover coins. How many coins does the parrot get?

Page 23: CHAPTER 9B — Expressions and Arithmetic Operators

 Source  URL:  http://chortle.ccsu.edu/java5/Notes/chap09B/ch09B_1.html  Saylor  URL:  http://www.saylor.org/courses/cs101/#3.3  ©  Bradley  Kjell     Saylor.org  Used  by  permission.     Page  23  of  25  

Answer: 123 coins / 5 pirates is 24 coins per pirate. 123 % 5 is 3 coins left over for the parrot.

Constants Often in a program you want to give a name to a constant value. For example you might have a tax rate of 0.045 for durable goods and a tax rate of 0.038 for non-durable goods. These are constants, because their value is not going to change during a run of the program. It is convenient to give these constants a name. This can be done:

The reserved word final tells the compiler that the value will not change. The names of constants follow the same rules as the names for variables. (Programmers sometimes use all capital letters for constants; but that is a matter of personal style, not part of the language.) Now the constants can be used in expressions like: taxamount = gross * DURABLE ;

But the following is a syntax error: DURABLE = 0.441; // try (and fail) to change the tax rate.

In your programs, use a named constant like DURABLE rather than using a literal like 0.441. There are two advantages in doing this: ▪ Constants make your program easier to read and check for correctness. ▪ If a constant needs to be changed (for instance if the tax rates change) all you

need to do is change the declaration of the constant. You don't have to search through your program for every occurence of a specific number.

Page 24: CHAPTER 9B — Expressions and Arithmetic Operators

 Source  URL:  http://chortle.ccsu.edu/java5/Notes/chap09B/ch09B_1.html  Saylor  URL:  http://www.saylor.org/courses/cs101/#3.3  ©  Bradley  Kjell     Saylor.org  Used  by  permission.     Page  24  of  25  

QUESTION 18: Could an ordinary variable be used to give a value a name? What is another advantage of using final?

Page 25: CHAPTER 9B — Expressions and Arithmetic Operators

 Source  URL:  http://chortle.ccsu.edu/java5/Notes/chap09B/ch09B_1.html  Saylor  URL:  http://www.saylor.org/courses/cs101/#3.3  ©  Bradley  Kjell     Saylor.org  Used  by  permission.     Page  25  of  25  

Answer: Yes. But final prevents any accidental change to a constant.

End of the Chapter The remainder of this chapter is a list of subjects you may wish to review. Click on a subject that interests you to go to where it was discussed.

▪ Table of operators and their precedence. ▪ What an operand is. ▪ What a subexpression is. ▪ Rule for whether an operator is floating point or integer. ▪ Integer division. ▪ The remainder operator. ▪ The final reserved word.