Sub topic 3
Arithmetic, Remainder, and String Concatenation
Java can calculate numbers and join text. An operator is a symbol that tells Java what action to perform. An operand is a value the operator acts on. Together, operands and operators can form an expression, which produces a result.
For example, in 6 + 2, the operator is +, the operands are 6 and 2, and the result is 8.
Arithmetic operators
Arithmetic operators work with numbers.
| Operator | Action | Example | Result |
|---|---|---|---|
| `+` | Add | `6 + 2` | `8` |
| `-` | Subtract | `6 - 2` | `4` |
| `*` | Multiply | `6 * 2` | `12` |
| `/` | Divide | `6 / 2` | `3` |
| `%` | Find the remainder | `7 % 2` | `1` |
The remainder is what is left after division into whole groups. For example, 7 % 2 is 1 because three groups of two use six, with one left over. The % operator does not calculate a percentage.
When both operands of / are integers, Java discards the fractional part of the result. An integer is a whole number, such as 7 or -2. So 7 / 2 is 3, while 7.0 / 2 is 3.5.
For negative integers, Java discards the fractional part toward zero. Thus, -7 / 2 is -3, and -7 % 2 is -1. The remainder has the sign of the left operand when it is not zero.
Join text with `+`
A String is a value that holds text. Java also uses + to join a String with another value. This joining is called concatenation.
For example, "Score: " + 5 produces the text Score: 5. Java turns the number into text for the join.
The grouping matters when numbers and text are mixed:
"Score: " + 2 + 3producesScore: 23. The first+joins text and2; the next one joins that text and3."Score: " + (2 + 3)producesScore: 5. Parentheses make Java add the numbers before joining them to the text.
Try it
Save this program as ArithmeticDemo.java, then compile and run it.
public class ArithmeticDemo {
public static void main(String[] args) {
int slices = 17;
int people = 5;
int each = slices / people;
int left = slices % people;
System.out.println("Slices per person: " + each);
System.out.println("Slices left: " + left);
System.out.println("Total check: " + (each * people + left));
System.out.println("Without parentheses: " + 2 + 3);
System.out.println("With parentheses: " + (2 + 3));
}
}The output is:
Slices per person: 3
Slices left: 2
Total check: 17
Without parentheses: 23
With parentheses: 5Each person gets three whole slices, and two remain. The total check multiplies the share by the number of people, then adds the remainder.
Practice
Exercise
What are the results of 19 / 4 and 19 % 4?
Show answer
19 / 4 is 4, and 19 % 4 is 3. Four groups of four use 16, leaving 3.
Exercise
What text does "Total: " + (4 + 2) produce? What happens if you remove the parentheses?
Show answer
It produces Total: 6. Without the parentheses, it produces Total: 42 because each number is joined to the text.