Java Programming/Basic Arithmetic

From Wikibooks, the open-content textbooks collection

Jump to: navigation, search
Navigate Basic Arithmetic topic:

( v d e )

Beginners Topics:

[edit] Using Arithmetic Within Java

In order to do arithmetic in Java, one must first declare at least one integer. Typically one declares an integer and assigns it a value before any arithmetic is done. Here's an example of declaring an integer variable:

int x = 5;

After creating a variable, one can manipulate its value by using Java's operators (the examples use our previously declared x variable):

Operator Function Example input Example output
+ Addition x + 2 7
- Subtraction x - 4 1
* Multiplication x * 3 15
/ (Integer) Division x / 2 2
 % Modulo (Remainder)[1] x % 2 1
++ Preincrement by one ++x 6
-- Predecrement by one --x 4
++ Postincrement by one x++ 5
-- Postdecrement by one x-- 5

The division operator rounds towards zero: 5 / 2 is 2, and -5 / 2 is -2. The remainder operator has the same sign as the left operand; it is defined such that ((a / b) * b) + (a % b) is always equal to a. The preincrement, predecrement, postincrement, and postdecrement operators are special: they also change the value of the variable, by adding or subtracting one. The only difference is that preincrement/decrement returns the value of the variable after adding/subtracting 1; postincrement adds 1 after returning the expression. So if we executed

int x1 = 7;
int y1 = 2 * ++x1;
 
int x2 = 7;
int y2 = 2 * x2++;

both x1 and x2 would be 8, but y1 would be 16 and y2 would be 14. y1 was calculated after 1 was added to the value of x1, and y2 was calculated before 1 was added to x2. All increment/decrement operators can be used alone to add or subtract 1 from a variable. For example one can write just x++; or ++x; to add 1 to x.

Note that by inserting these example statements into Java source code, no output would be produced. To print the results of a math operation, you would use:

System.out.println(x + 2);

When using several operators in the same expression, one must consider Java's order of precedence. Java uses the standard PEMDAS (Parenthesis, Exponents, Multiplication and Division, Addition and Subtraction) order. When there are multiple instances of the same precedence, Java reads from left to right. Consider what the output of the following code would be:

System.out.println(10 * 5 + 100 / 10 - 5 + 7 % 2);

The following chart shows how Java would compute this expression:

10 * 5 + 100 / 10 - 5 + 7 % 2
  \ /
  50   + 100 / 10 - 5 + 7 % 2
            \ /
  50   +    10    - 5 + 7 % 2
                         \ /
  50   +    10    - 5 +   1
     \    /
       60         - 5 +   1
          \      /
           \    /
             55      +   1
               \        /
                \      /
                 \    /
                   56

The output would be "56".

Besides performing mathematical functions, there are also operators to assign numbers to variables (each example again uses the variable initialized as x=5):

Operator Function Example input Example output
= Assignment x = 3 3
+= Assign x plus another integer to itself x += 5 10
-= Assign x minus another integer to itself x -= 4 1
*= Assign x multiplied by another integer to itself x *= 6 30
/= Assign x divided by another integer to itself x /= 5 1

A third kind of operator does not return or assign numbers. The following are Java's evaluation operators, which either return "true" or "false.":

Operator Function Example input Example output
< Less than x < 7 true
> Greater than x > 5 false
<= Less than or equal to x <= 5 true
>= Greater than or equal to x >= 1 true
== Equal to x == 5 true
 != Not equal to x != 5 false

These statements come in handy when using if-else, statements and for and while loops. What would the output of the following code be?

public class Test {
   public static void main(String[] args) {
     int x = 4;
     int y = 4;
     int z = 6;
     x++;
     y *= 2;
     z += x;
     if (x <= y) {
       System.out.println("x is less than or equal to y.");
     }
     if (z <= y) {
       System.out.println("z is less than y.");
     }
     if (x != z) {
       System.out.println("x is not equal to z.");
     }
   }
 }

This code would print:

x is less than or equal to y.
x is not equal to z