Arithmetic Operations in Java

To perform arithmetic operations in Java, place the operation on the right side of the assignment operator (=), and a variable on the left. To assign 7 to an integer variable x:

int x;

x = 3 + 4;

The basic arithmetic operations are:

+ add

- subtract

* multiply

/ divide

Exercise 5:

Write an application named Exercise5 that declares two doubles. Assign the value of 3.0 to the first and 6.0 to the second. Print out the sum, difference, product, and quotient of the two numbers, like this:

3.0 + 6.0 = 9.0
3.0 - 6.0 = -3.0
3.0 * 6.0 = 18.0
3.0 / 6.0 = .5

Of course you should not hard code the answers -- calculate them.

For the solution, click here.

 

 

Java also provides two "shortcut" arithmetic operations: one that increments (adds one to) a number, and one that decrements (subtracts one from) a number.

The incrementation operation is

x++

or

++x

Both of these are the same as

x = x + 1

The decrementation operation is

x--

or

--x

Both of these are the same as

x = x - 1

Exercise 6:

Change your previous exercise by adding 1 to x (using the incrementation operator) after the first output line, then decrementing x again (using the decrementation operator) after the second line, so that the output is:

3.0 + 6.0 = 9.0
4.0 - 6.0 = -2.0
3.0 * 6.0 = 18.0
3.0 / 6.0 = .5

For the solution, click here.

For the next syntax lesson, click here.