Chapter 2 Operator Meaning Type Example Addition Binary
Chapter 2
Operator Meaning Type Example + Addition Binary total = cost + tax; - Subtraction Binary cost = total – tax; * Multiplication Binary tax = cost * rate; / Division Binary sale. Price = original / 2; % Modulus Binary remainder = value % 5;
§ The operators are called binary operators because they must have two operands. § The arithmetic operators work as one would expect. § It is an error to try to divide any number by zero. § When working with two ints the answer is always and int § When working with two integer operands, the division operator requires special attention
§ What is 1/2? § 5/2? § 22/4?
With modular division, the answer is the remainder 21%5 7%4 18%3 47%9 63%7 2%8
Operator Associativity Example Result (unary negation) Right to left x = -4 + 3; -1 * / % Left to right x = -4 + 4 % 3 * 13 + 2; 11 + - Left to right x = 6 + 3 – 4 + 6 * 3; 23 § You can group with parenthesis
int mystery; mystery = 6; mystery = mystery + 1; //adds one to mystery = mystery * 5; //multiplies the current value by 5 mystery = mystery / 3; //divides the current value by 3 What is the value of mystery at the conclusion?
Operator Example Equivalent Value of variable after operation += x += 5; x = x + 5; The old value of x plus 5. -= y -= 2; y = y – 2; The old value of y minus 2 *= z *= 10; z = z * 10; The old value of z times 10 /= a /= b; a = a / b; The old value of a divided by b. c = c % 3; The remainder of the division of the old value of c divided by 3. %= c %= 3;
§ Create a new class called operations test § Create a new int variable and assign it a value § Add 5 to the value and print it out § Divide the value by 2 and print it out § Multiply the value by 4 and print it out § Subtract the value by 6 and print it out § Modularly divide by 2 and print it out § *** use println on each print and disply a message saying what you accomplished. Ex. Add 5: 17
- Slides: 9