Academic Java    Java Tutorial  >  Basics  >  arithmetic expressions

arithmetic expressions Example

The variable i is initialized and its value is used to assign values to the variable j.

Each of the assignments to j has an arithmetic expression to the right of the assignment operator =.

An arithmetic expression is evaluated during the run to yield a value.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
import java.awt.*;

class ArithmeticExpressionsExample1 {

   public static void main(String[] args) {

      int i = 13, j;

      j = i + 3;

      j = i - 3;

      j = i * 2;

      j = i / 3;

      j = i % 4;

   }

}

9-17 By running the program you will see the results of the arithmetic expressions and their assignment to j

7 Variable i is initialized with the value 13. The operator = is the assignment operator. We say the variable is assigned a value.
The variable j is declared, that is it is made known to the compiler but it is not assigned a value yet.

9 The operator + is the addition operator.
The variable j is assigned the value 16 that is the sum of the value of i and 3.

11 The operator - is the subtraction operator.
The variable j is assigned a value 10 that is the value of i minus 3.

13 The operator * is the multiplication operator.
The variable j is assigned a value 26 that is the value of i multiplied by 2.

15 The operator / is the division operator.
The variable j is assigned a value 4 that is the value of i divided by 3. Division of integers can result in truncation i.e. any remainder is discarded.

17 The operator % is the remainder operator.
The variable j is assigned a value 1 that is the remainder of the value of i divided by 4.

* arithmetic expressions Examples