Operators and Strings: Integer Division, Remainders and Text
Learn arithmetic and comparison operators, the surprises of integer division and negative remainders, and how Java strings behave, with results checked against Python.
In this lesson you will
- Use arithmetic and comparison operators
- Predict integer division and remainder
- Work with String methods
- Build text efficiently
About 28 minutes
Splitting the rental fee
Hana wants to split a 100 euro group booking between 3 riders, and the program says each pays 33. Where did the missing euro go? In Java, dividing two int values gives an int, and the fractional part is thrown away. Operators look simple, and a few of their rules deserve attention before you trust a calculation.
| Operator | Meaning | Example |
|---|---|---|
| + – * / | Arithmetic | 7 / 2 is 3 for ints |
| % | Remainder | 7 % 2 is 1 |
| == != | Equal, not equal | bikes == 12 |
| < >= | Comparison | bikes >= 10 |
| && || ! | And, or, not | open && !raining |
| += ++ | Shortcuts | count++ |
The remainder operator % gives what is left after division, and for negative numbers the sign follows the first number, so -7 % 3 is -1 in Java. Python behaves differently, which surprises people who know both. Strings are objects, written in double quotes. A String can never be changed after it is made, which is called immutability: methods like toUpperCase return a new string and leave the old one alone. Joining strings with + inside a loop creates many throwaway strings, so for building long text you use StringBuilder.
public class Main {
public static void main(String[] args) {
System.out.println("100 / 3 = " + (100 / 3));
System.out.println("100 % 3 = " + (100 % 3));
System.out.println("100.0 / 3 = " + (100.0 / 3));
System.out.println("-7 / 2 = " + (-7 / 2) + ", -7 % 3 = " + (-7 % 3));
System.out.println("floorMod(-7, 3) = " + Math.floorMod(-7, 3));
String name = "Hana's Bikes";
String upper = name.toUpperCase();
System.out.println(name + " -> " + upper + " (length " + name.length() + ")");
System.out.println("contains 'Bike': " + name.contains("Bike") + ", index of 's': " + name.indexOf('s'));
System.out.println(name.substring(0, 4) + "|" + name.replace("Bikes", "Cycles"));
StringBuilder sb = new StringBuilder();
for (int i = 1; i <= 5; i++) { sb.append(i).append(i < 5 ? "," : ""); }
System.out.println("built: " + sb + " (" + sb.length() + " chars)");
String block = """
Rental terms:
- bring a helmet
""";
System.out.print(block);
System.out.println("same text? " + ("abc".equals("ab" + "c")));
}
}
100 / 3 = 33
100 % 3 = 1
100.0 / 3 = 33.333333333333336
-7 / 2 = -3, -7 % 3 = -1
floorMod(-7, 3) = 2
Hana's Bikes -> HANA'S BIKES (length 12)
contains 'Bike': true, index of 's': 5
Hana|Hana's Cycles
built: 1,2,3,4,5 (9 chars)
Rental terms:
- bring a helmet
same text? true
Dividing 100 by 3 as ints gave 33 with a remainder of 1, so 3 times 33 plus 1 is back to 100: the missing euro is the remainder. With a decimal point, 100.0 / 3 gave 33.333333. Java truncates integer division towards zero, so -7 / 2 gave -3 and not -4, and -7 % 3 gave -1. When you want the mathematical modulus that is never negative, Math.floorMod(-7, 3) gives 2, the answer that Python gives for -7 % 3.
The string “Hana’s Bikes” has 12 characters, and toUpperCase produced a new string without touching the original, as the first part of the output line shows. The StringBuilder made “1,2,3,4,5”, which is 9 characters, without creating a string for each step. The text block, written between triple quotes, keeps its line breaks and removes the shared indentation, which makes multi-line text easy to read in code. Finally, strings must be compared with equals and not ==, because == compares whether two variables point at the same object, and equals compares the characters.
Check by hand: 3 x 33 = 99, and 100 – 99 = 1, the remainder. For -7 / 2, the exact answer is -3.5, and truncating towards zero gives -3. For the remainder, -7 = 2 x (-3) + (-1), so the remainder is -1. Python would print -4 and 2 for those two, because Python rounds down, so the two languages agree on the rule a = b x q + r and differ in the choice of q.
If either number is a double, Java divides as decimals. Convert before dividing, for example (double) total / riders.
Compare strings with a.equals(b). Using == can appear to work for literals and then fail for strings built at run time.
Every program in this lesson was compiled and run with OpenJDK 21 while the course was written. Java releases twice a year, so check the official Java documentation for the current version and for features added after Java 21. Text blocks need Java 15 or later.
Practice
Split 250 euro between 7 riders using int division and the remainder, then with decimals. Print the name backwards using StringBuilder.reverse(). Check what Math.floorMod(-1, 12) gives and think about where you might use it, for example to wrap around the hours of a clock.
Check what you learned
Five quick questions. Pick an answer and you will see straight away whether it is right and why.
What is 100 / 3 with two ints?
- 33.33
- 34
- 3
- 33
The fraction is dropped.
What is -7 % 3 in Java?
- 2
- 1
- -1
- -2
The remainder takes the sign of the first number.
Why use StringBuilder in a loop?
- It encrypts text
- It is required
- It avoids creating many temporary strings
- It sorts text
Strings are immutable.
How should you compare two strings?
- With ==
- With equals
- With the + sign
- With length only
== compares references.
What does a text block keep?
- Only one line
- Line breaks and relative indentation
- Only numbers
- Nothing
It removes shared leading spaces.
Summary
- Integer division truncates and % gives the remainder with the sign of the first number.
- Use Math.floorMod for a never-negative modulus.
- Strings are immutable; use StringBuilder to build text.
- Compare strings with equals.
Questions
What does immutable mean?
The object cannot change after creation. Methods that look like changes return a new object.
Is string concatenation with + bad?
It is fine for a few joins. In long loops, StringBuilder is more efficient.
Why does Java truncate integer division?
It follows the rule of most languages, where int division returns an int. Convert to double when you need decimals.
