X Tutup
Skip to content

Latest commit

 

History

History
380 lines (284 loc) · 9.93 KB

File metadata and controls

380 lines (284 loc) · 9.93 KB

Arithmetic Operators

Java can do math. (and that should not surpirise you!) And many early programming exercises you will come across deal with doing fairly easy math. There are ways to do lots of useful things with numbers.

Now, remember, there are two basic kinds of numbers, integers and floating-point. And these operators work on both kinds.

Basics

Operator Name Description

+

Addition

Add two values

-

Subtraction

Subtract one from another

*

Multiplication

Multiply 2 values

/

Division

Divide 2 numbers

%

Modulus

Remainder after division

++

Increment

Increase value by 1

- -

Decrement

Decrease value by 1

Say we needed to multiply two numbers. Maybe 2 times 3. Now we could easily write a program that printed that result.

System.out.println(2 * 3);

And that will print 6 on the console. But maybe we’d like to make it a little more complete.

int a = 2;
int b = 3;
// Multiply a times b
int answer = a * b;
System.out.println(answer); // -> 6

Here we have set up two variables, a and b, for our operands and a final answer variable. But, it’s pretty much the same as the more simple example above.

Using this as a model, how would you write programs to solve these problems?

Exercises:

  • Exercise 1: Subtract A from B and print the result

  • Exercise 2: Divide A by B and print the result

  • Exercise 3: Use an operator to increase A by 1 and print result

  • Exercise 4: Find remainder of A of b

int a = 9;
int b = 3;

int L1 = b - a;
int L2 = a / b;
int L3 = a + 1;
//or using increment
L3 = a++;
int L4 = a % b;
System.out.println(L1); // -> -6
System.out.println(L2); // -> 3
System.out.println(L3); // -> 10
System.out.println(L4); // -> 0
L4 = 10 % b;
System.out.println(L4); // now -> 1

Division and Remainder

We know that we can do regular division. If have a simple program like this, we know what to expect:

int a = 6 / 3; // -> 2
int a = 12 / 3; // -> 4
int a = 15 / 3; // -> 5
int a = 10 / 4; // -> 2 (what??)

When we are dividing int_s, we always get an _int as a result. So, somewhat confusingly, when we evaluate 10 / 4 we get 2. (and remember in school when the teacher would say, "10 / 4 is 2 with a remainder of 2"?? yes, remainders aare still with us.)

But sometimes, we have a need to know what the remainder of an integer division is. The remainder operator % (the percent sign), despite its appearance, is not related to percents.

The result of a % b is the remainder of the integer division of a by b. So as above, if we evaluate 10 % 4 we will get the remainder of 2.

System.out.println( 5 % 2 ); // 1, a remainder of 5 divided by 2
System.out.println( 8 % 3 ); // 2, a remainder of 8 divided by 3

Now what’s this about '%' (the remainder) operator?

int a = 3;
int b = 2;
// Modulus (Remainder)
int answer = a % b;
System.out.println(answer); // -> 1
int a = 19;
int b = 4;
// Remainder
int answer = a % b;
System.out.println(answer); // -> 3
int a = 4;
int b = 4;
// Remainder

for (a = 4; a < 13; a++) {
    System.out.println(a + " " + (a % b)); // would produce
}
    // output of
    // 4 0
    // 5 1
    // 6 2
    // 7 3
    // 8 0
    // 9 1
    // 10 2
    // 11 3
    // 12 0

(This example has a loop more on loops ahead. It’s how we control repeating things in code.)

Notice how a changes, but b stays the same. The result of a % b is always less than b. This is because the result is the remainder of the division of a by b. So, when a is 4, 4 % 4 is 0 (4 goes into 4 once, with no remainder). When a is 5, 5 % 4 is 1 (4 goes into 5 once, with a remainder of 1). When a is 6, 6 % 4 is 2 (4 goes into 6 once, with a remainder of 2). When a is 7, 7 % 4 is 3 (4 goes into 7 once, with a remainder of 3). When a is 8, 8 % 4 is 0 (4 goes into 8 twice, with no remainder). When a is 9, 9 % 4 is 1 (4 goes into 9 twice, with a remainder of 1). When a is 10, 10 % 4 is 2 (4 goes into 10 twice, with a remainder of 2). When a is 11, 11 % 4 is 3 (4 goes into 11 twice, with a remainder of 3). When a is 12, 12 % 4 is 0 (4 goes into 12 three times, with no remainder).

This is a useful operator for many things, including determining if a number is even or odd.

Order is Important

A strange thing about these operators is the order in which they are evaluated. Let’s take a look at this expression.

6 × 2 + 30

We can do this one of two ways:

  • Say we like to do multiplication (I know, who is that?)

    • we would then do the "6 times 2" part first, giving us 12.

    • then we’d add the 30 to 12 giving us 42 [1]

  • But say we don’t like multiplication, and want to save it for later…​

    • we would add 2+30 first, giving us 32

    • and then we multiply it by 6, and, whoa, we get 192!

Wait! Which is right? How can the answers be so different, depending on the order we do the math in? Well, this shows us that the Order of Operations is important. And people have decided upon that order so that this kind of confusion goes away.

Basically, multiply and divide are higher priority than add and subtract. And exponents (powers) are highest priority of all.

There is a simple way to remember this.

P.E.M.D.A.S

Use this phrase to memorize the default order of operations in Java.

Please Excuse My Dear Aunt Sally

  • Parenthesis ( )

  • Exponents 23

  • Multiplication * and Division /

  • Addition + and Subtraction -

Warning

Divide and Multiply rank equally (and go left to right) So, if we have "6 * 3 / 2", we would multiply first and then divide. "6 * 3 / 2" is 9

Add and Subtract rank equally (and go left to right) So if we have "9 - 6 + 5", we subtract first and then add. "9 - 6 + 5" is 8

Problem: Order of Operations

30 + 6 × 2 How should this be solved?

Right way to solve 30 + 6 × 2 is first multiply, 6 × 2 = 12, then add 30 + 12 = 42

This is because the multiplication is higher priority than the addition, even though the addition is before the multiplication in the expression. Let’s check it in Java:

int result = 30 + 6 * 2;
System.out.println(result);

This gives us 42.

Now there is another way to force Java to do things "out of order" with parenthesis.

Problem: Using Parentheses

(30 + 6) × 2

What happens now?

int result = (30 + 6) * 2;
System.out.println(result);

What’s going to happen? Will the answer be 42 or 72? Try it in jshell and find out:

jshell> int result = (30 + 6) * 2;
jshell> System.out.println(result);
72

The parenthesis forces the addition to be done first, giving us 36, and then multiplying by 2 gives us 72.

So make it easy on yourself, always use parenthesis to make it clear what you want done first.

Java Math Class

There is a useful thing in Java called the Math class which allows you to perform mathematical tasks on numbers.

  • Math.PI; - returns 3.141592653589793

  • Math.round(4.7); // returns 5

  • Math.round(4.4); // returns 4

  • Math.pow(x, y) - the value of x to the power of y - xy

  • Math.pow(8, 2); // returns 64

  • Math.sqrt(x) - returns the square root of x

  • Math.sqrt(64); // returns 8

Important

What does "returns" mean?

When we ask a 'function' like sqrt to do some work for us, we have to code something like:

double squareRootTwo = Math.sqrt(2.0);
System.out.println(squareRootTwo);

We will get "1.4142135623730951" in the output. That number (squareRootTwo) is the square root of 2, and it is the result of the function and what the function sqrt "returns"'.

More on functions later. And more on the Math class later.

And more on return later.

Math.pow() Example

Say we need to compute "62 + 5"

double result = Math.pow(6,2) + 5;
System.out.println(result); // -> 41.0

What will the answer be? 279936.0 or 41.0?

How did Java solve it?

Well, 6^2 (6 squared) is the same as 6 * 6. And 6 * 6 = 36, then add 36 + 5 = 41.

You’ll learn a lot more about working with numbers in your career as a coder. This is really just the very basic of beginnings.

Chapter Exercises

Try these exercises in jshell to practice arithmetic operators:

Exercise 1: Basic Arithmetic

Practice all the basic operators:

int a = 20;
int b = 6;

System.out.println("a + b = " + (a + b));
System.out.println("a - b = " + (a - b));
System.out.println("a * b = " + (a * b));
System.out.println("a / b = " + (a / b));
System.out.println("a % b = " + (a % b));

What happens with integer division? Why is 20/6 = 3?

Exercise 2: Order of Operations

Predict the results before running:

int result1 = 5 + 3 * 2;
int result2 = (5 + 3) * 2;
int result3 = 10 - 4 / 2 + 1;
int result4 = (10 - 4) / (2 + 1);

System.out.println("5 + 3 * 2 = " + result1);
System.out.println("(5 + 3) * 2 = " + result2);
System.out.println("10 - 4 / 2 + 1 = " + result3);
System.out.println("(10 - 4) / (2 + 1) = " + result4);

Exercise 3: Math Class Methods

Experiment with Math class methods:

double radius = 5.0;
double area = Math.PI * Math.pow(radius, 2);
double circumference = 2 * Math.PI * radius;

System.out.println("Circle with radius: " + radius);
System.out.println("Area: " + area);
System.out.println("Circumference: " + circumference);
System.out.println("Square root of 64: " + Math.sqrt(64));
System.out.println("4 to the power of 3: " + Math.pow(4, 3));

Exercise 4: Increment and Decrement

Practice with ++ and — operators:

int counter = 10;
System.out.println("Initial counter: " + counter);

counter++;
System.out.println("After counter++: " + counter);

counter--;
System.out.println("After counter--: " + counter);

System.out.println("Using ++counter: " + (++counter));
System.out.println("Using counter++: " + (counter++));
System.out.println("Final counter: " + counter);

Notice the difference between counter and counter


1. The answer to life, the universe and Everything.
X Tutup