740 likes | 983 Views
Chapter 2 JAVA FUNDAMENTALS CONT’D. 1. ARITHMETIC OPERATORS. Java provides many operators that are useful for manipulating data and performing arithmetic operations. Operators can be classified as unary, binary, or ternary depending on the number of operands the operator requires.
E N D
ARITHMETIC OPERATORS Java provides many operators that are useful for manipulating data and performing arithmetic operations. Operators can be classified as unary, binary, or ternary depending on the number of operands the operator requires. Unary operators require a single operand. Binary operators require two operands. Ternary operators require three operands. 2
ARITHMETIC OPERATORSNegation Operator (–) The negation operator is a unary operator that negates the value of its operand. The second assignment statement in the segment below assigns the value –50 to that variable named angle2. Note that after this assignment, angle1 still has the value 50. angle1 = 50; angle2 = –angle1; 3
ARITHMETIC OPERATORSAddition Operator (+) The addition operator is a binary operator that returns the sum of its two operands. In the last statement of the segment below the value in amount is added to the value in bonus and the resulting value, 11854.73, is stored in total. The variable amount will still have the value 11354.40 and bonus will have the value 500.33 at the end of the segment. amount = 11354.40; bonus = 500.33; total = amount + bonus; 4
ARITHMETIC OPERATORSSubtraction Operator(–) The subtraction operator is a binary operator that returns the result of subtracting its right operand from its left operand. The following statement subtracts the value 27 from 70 and stores the result (43) in number. number = 70 – 27; 5
ARITHMETIC OPERATORSMultiplication Operator (*) The multiplication operator is a binary operator that returns the product of its two operands. In the following segment the value in rate is multiplied by the value in time and the result, 121.5, is stored in distance. The values of rate and time are not changed by the multiplication operator. rate = 40.5; time = 3; distance = rate * time; 6
ARITHMETIC OPERATORSDivision Operator (/) The division operator is a binary operator that returns the quotient of its left operand divided by its right operand. In the statement below 160 is divided by 2 and the resulting value, 80, is assigned to the variable x. x = 160 / 2; 7
ARITHMETIC OPERATORSDivision Operator (/) If both operands of the division operator are integers the quotient is an integer. The fractional part is truncated. In the statement below, the expression 161 / 2 has the value 80. This is because both operands of the division operator are of type int. The .5 is discarded. The value 80 is assigned to x. x = 161 / 2; 8
ARITHMETIC OPERATORSDivision Operator (/) If at least one of the operands of the division operator is a floating-point type the quotient is a floating-point type. In the segment below, the expression 161.0 / 2 has the value 80.5. This value is stored in x. The expression 12 / z has the value 4.8. This value is stored in y. double z = 2.5; x = 161.0 / 2; y = 12 / z; 9
ARITHMETIC OPERATORSDivision Operator (/) Problem: What is the data type of the result of players / maxPlayers in the statement below? teams = players / maxPlayers; Answer: 10
ARITHMETIC OPERATORSModulus Operator(%) The modulus operator is a binary operator that returns the remainder of a division operation. We can use this operator to find the number of items left over after a division operation. The following statement divides 12 by 10 and stores the remainder of the division (2) in nextDigit. nextDigit = 12 % 10; 11
THE Math CLASSThe pow Method Java does not have an exponent operator. To raise a number to a power we can use the pow method of the Math class. You can think of a method as a routine that performs a specific operation. The pow method takes two double arguments. Arguments are data values sent to a method. The pow method raises the value of the first argument to the power of the second argument and returns the result of this calculation as a value of type double. 12
THE Math CLASSThe pow Method Suppose that we want to calculate the volume of a cube. The volume of a cube, v, is specified by the algebraic formula: v = s3 where s is the length of the side of the cube. In our program, if we have the side length of the cube stored in a variable named side, and we have already declared a variable named volume to hold the calculated volume, we could specify this calculation as follows: volume = Math.pow(side, 3); 13
THE Math CLASSThe pow Method volume = Math.pow(side, 3); Math.pow(side,3) is a call to the pow method which is a member of the Math class. This call is an expression, the value of this expression is the double value returned by the method. In our case, this value is assigned to the variable volume. Make sure volume is declared as type double or you will get a syntax error. Suppose side has the value 3.3, the value returned by the method call and assigned to volume is 35.937. 14
THE Math CLASSThe pow Method The value returned by the pow method can be used anywhere a double value can be used. For example the algebraic expression j = y - (x + 2)6 could be encoded in Java as: j = y - Math.pow(x + 2, 6); 15
THE Math CLASSThe sqrt Method Java does not have a square root operator. We can use the sqrt method of the Math class to find the square root of a number. The sqrt method takes a double argument and returns the square root of the argument as a value of type double. 16
THE Math CLASSThe sqrt Method For example the algebraic expression: Could be encoded in Java as: z = 4 * Math.sqrt(a + b); 17
OPERATOR PRECEDENCE & ASSOCIATIVITY An expression may consist of a literal value, a variable, or be a combination of operators and operands. The evaluation of some expressions like 4 + 21 is straightforward. Others are not so straightforward, for instance 16 - 8 / 4. The value of this expression depends on whether the subtraction or the division is performed first. 18
OPERATOR PRECEDENCE & ASSOCIATIVITY In Java, mathematical expressions are processed from left to right. When two operators share an operand, the operation specified by the operator with the highest precedence is performed first. *** See Table 2-8 and Appendix C of the text 19
OPERATOR PRECEDENCE & ASSOCIATIVITY Continued on the next slide 20
OPERATOR PRECEDENCE & ASSOCIATIVITY Division has higher precedence than subtraction. In the expression below, the division, 8 / 4, is performed first, producing a quotient of 2. Then 2 is subtracted from 16 producing a result of 14. 16 - 8 / 4 22
OPERATOR PRECEDENCE & ASSOCIATIVITY If two operators sharing an operand have the same precedence, the operators work according to their associativity. Associativity is either left-to-right or right-to-left. For instance, if a multiplication and division operator share an operand these operations will be performed left-to-right since multiplication and division associate from left-to-right. 23
OPERATOR PRECEDENCE & ASSOCIATIVITY Problem: What is the value of the following expression? ____ 2 + 3 * 4 24
OPERATOR PRECEDENCE & ASSOCIATIVITY Problem: What is the value of the following expression? ____ 17 – 7 % 4 * 2 25
OPERATOR PRECEDENCE & ASSOCIATIVITY Problem: What is the value of the following expression? ____ 15 + 20 / 8 + 6 * 2 26
GROUPING WITH PARENTHESES You may enclose an expression in parentheses to ensure that it is evaluated before other expressions that involve its operands. Example: x = 10 – (8 – 4); The value of the expression, 10 – (8 – 4), is 6. Without the parentheses, the expression is 10 – 8 – 4, in this expression 8 would have been subtracted from 10 first, resulting in a value of 2, and then 4 would have been subtracted from 2, to produce the value –2. 27
GROUPING WITH PARENTHESES Example: If you wanted to encode the following algebraic expression in Java: You could write: y = (4 * a * c – d) / (2 – b); Without the parentheses, the equation implemented would be: 28
COMBINED ASSIGNMENT OPERATORS In programs, it is quite common to get the current value of a variable, modify it, and then assign the resulting value back to the original variable. Example: x = x + 10; This statement specifies that the value 10 is to be added to the current contents of the variable x and the resulting value becomes the new contents of x. Effectively, this statement increases the value of the variable x by 10. 29
COMBINED ASSIGNMENT OPERATORS Java provides a shorthand way to write this statement using the combined assignment plus equals operator, +=. Instead of writing the statement: x = x + 10; We can write: x += 10; The (+=) operator adds the value of its right operand to the current value of its left operand and stores the result in the left operand. 30
COMBINED ASSIGNMENT OPERATORS The minus equals operator, –= subtracts the value of its right operand from the current value of its left operand and stores the result in the left operand. For example: balance = balance – withdrawals; Could be written: balance –= withdrawals; 31
COMBINED ASSIGNMENT OPERATORS The left operand of a combined assignment operator is used as both the left operand of the specified arithmetic operation and the storage location for the result of the operation. The left operand of a combined assignment operator must be a variable. 32
COMBINED ASSIGNMENT OPERATORS *** See Table 2-13 of the text for more about the combined assignment operators and their usage The times equal operator, *=, multiplies the value of its right operand by the current value of its left operand and stores the result in the left operand. The divide equal operator, /=, divides the current value of its left operand by the value of the right operand and stores the result in the left operand. The mod equal operator, %=, divides the current value of its left operand by the value of the right operand and stores the remainder of the division in the left operand. 33
COMBINED ASSIGNMENT OPERATORS The combined assignment operators have lower precedence than the arithmetic operators +, –, *, /, and %. *** See Appendix C of the text For example the statement: w /= b + 1; Is equivalent to: w = w / (b + 1); 34
COMBINED ASSIGNMENT OPERATORS Precedence & Associativity Continued on the next slide 35
COMBINED ASSIGNMENT OPERATORS Precedence & Associativity Here are the combined assignment operators. 36
CONVERSION BETWEEN PRIMITIVE DATA TYPES Java is a strongly typed language. The Java compiler checks that the values assigned to variables are of a type compatible with the variables data type. 37
CONVERSION BETWEEN PRIMITIVE DATA TYPES Example: The compiler rejects the assignment statement in the segment below, saying “possible loss of precision”. double g = 13.9; int z; z = g; The compiler will not allow this assignment, because the data type double can hold a larger value than a variable of type int can hold. 38
CONVERSION BETWEEN PRIMITIVE DATA TYPES In Java the numeric data types are ranked. One data type outranks another if it can hold a larger value. *** See Figure 2-6 of the text 39
CONVERSION BETWEEN PRIMITIVE DATA TYPES In general, Java does not automatically perform narrowing conversions. A narrowing conversion is a conversion “from” a higher-ranking data type to a lower-ranking data type. 40
CONVERSION BETWEEN PRIMITIVE DATA TYPES double g = 13.9; int z; z = g; That is the problem with the assignment statement highlighted above. We are asking that a value of type double be stored in a variable of type int. This is a narrowing conversion - a compiler error occurs. It is an error to assign a double value to a variable of type int. 41
CONVERSION BETWEEN PRIMITIVE DATA TYPES Java automatically performs widening conversions. A widening conversion is a conversion “to” a higher-ranking data type. 42
CONVERSION BETWEEN PRIMITIVE DATA TYPES Example: The compiler automatically converts the value of type int to a value of type float in the assignment statement at the bottom of the segment below. This conversion is a widening conversion. (Remember an assignment does not change the right operand, the variable x still contains the 4-byte integer value 5 after the execution of the last statement.) int x = 5; float y; y = x; Here x is an int and y is a float. We are converting to a higher-ranking type. This is a widening conversion. 43
CONVERSION BETWEEN PRIMITIVE DATA TYPESThe Cast Operator The cast operator is a unary operator that allows the programmer to convert a value to a different data type. You can specify either a narrowing or a widening conversion using the cast operator. The cast operator is a parenthesized data type. It specifies that the operand that follows is to be converted to the data type inside the parentheses. 44
CONVERSION BETWEEN PRIMITIVE DATA TYPESThe Cast Operator When you convert a floating-point type to an integer type, any fractional portion is truncated (discarded). Note: The value is not rounded. The operand of the cast operator is not changed by the operation. A copy of the value is made that is of the specified data type. 45
CONVERSION BETWEEN PRIMITIVE DATA TYPESThe Cast Operator Example: The third statement of the segment below specifies that the computer make a copy of the value in g that is of type int, then assign this integer value to the variable z. At the end of the segment z contains the value 13 and g still contains the double value 13.9. double g = 13.9; int z; z = (int) g; 46
CONVERSION BETWEEN PRIMITIVE DATA TYPESThe Cast Operator Example: The last statement of the following segment casts the value of the integer value stored in number to a char before assigning it to rating. Remember Java is strongly typed; it will not automatically convert the value of an integer variable to a char. The value in number is not changed by the cast, a copy of the value in number is made that is in Unicode . int number = 65; char rating; rating = (char) number; 47
CONVERSION BETWEEN PRIMITIVE DATA TYPESThe Cast Operator Example: In the last statement of the segment below, a copy of the value in x is made that is of type double. This value, 22.0, is divided by the value in y, 8, the resulting value, 2.75, is assigned to g. Without the cast the result of the division would have been 2, an int. Java would have done a widening conversion and the value 2.0 would have been assigned to g. int x = 22, y = 8; double g; g = (double) x / y; 48
CONVERSION BETWEEN PRIMITIVE DATA TYPESThe Cast Operator Problem: Describe the automatic type conversions that occur in the following segment. Assuming that the segment is part of a complete Java program, is the segment syntactically correct? float m = 4; double d = m; int j; j = Math.pow(2, 3); Answer: 49
CONVERSION BETWEEN PRIMITIVE DATA TYPESAutomatic Type Conversion in Arithmetic Expressions When an arithmetic operator has operands of different data types, Java will temporarily convert the operand of the lower-ranking data type to the higher-ranking data type. The result of the operation will be the same data type as the higher-ranking operand. When values of type byte and short are used in arithmetic expressions, they are temporarily converted to type int. 50