Arithmetic And Assignment
Java has five basic arithmetic operators:
| Operator | Operation | Example |
|---|---|---|
+ | Addition | 7 + 2 gives 9 |
- | Subtraction | 7 - 2 gives 5 |
* | Multiplication | 7 * 2 gives 14 |
/ | Division | 7 / 2 gives 3 for integers |
% | Remainder | 7 % 2 gives 1 |
Calculate with two numbers
public class Main {
public static void main(String[] args) {
int first = 20;
int second = 6;
int difference = first - second;
int product = first * second;
int quotient = first / second;
int remainder = first % second;
System.out.println("Difference: " + difference);
System.out.println("Product: " + product);
System.out.println("Quotient: " + quotient);
System.out.println("Remainder: " + remainder);
}
}
Output:
Difference: 14
Product: 120
Quotient: 3
Remainder: 2
Each calculation has its own variable, so you can inspect or reuse any result later. Because first and second are integers, division produces the whole-number quotient.
Java also has compound assignments for updating an existing variable. For example, score += 5 is a shorter way to write score = score + 5. The longer form is often easier to read while you are getting comfortable with arithmetic.
Calculate an order total with multiplication and addition.