Java's operators are grouped by what they do. There are the arithmetic ones, the assignment ones, the comparison ones, the logical ones and the bitwise ones, plus a couple of oddities. The syntax will look familiar, but three of them behave in a way that will surprise you at least once.
The previous lesson in this module covered "How Does Type Casting and Numeric Promotion Work in Java?", and the next lesson in this module is about "How Do You Read User Input With the Scanner Class?", which covers how a program listens to what a person types.
What are the arithmetic operators?
You have addition, subtraction, multiplication, division and remainder, plus a minus sign that can sit in front of a single value. The one that you have to learn properly is division, because two whole numbers divide to a whole number.
int a = 17;
int b = 5;
System.out.println(a + b); // 22
System.out.println(a - b); // 12
System.out.println(a * b); // 85
System.out.println(a / b); // 3, because this is whole number division
System.out.println(a % b); // 2, which is the remainder
System.out.println((double) a / b); // 3.4
When you want a fraction as the answer, turn one of the two sides into a double before you divide. Turning the answer into a double afterwards is too late, because the fraction has already been thrown away.
What about the compound assignment operators?
Java has a short form for the common pattern of working something out and then storing it back.
int total = 100;
total += 25; // the same as total = total + 25
total -= 10;
total *= 2;
total /= 4;
total %= 7;
System.out.println(total);
The short form is not only shorter. It is also safer when the variable has a small type, because the compiler checks that the answer still fits inside it. It also reads well with text, because the line message += " more"; is clearer than the line message = message + " more";.
What is the difference between ++ and --?
Both of them add one or subtract one. The interesting part is when the change happens, and that only matters if you use the result of the expression.
int a = 5;
int b = a++; // b gets 5, and then a becomes 6
int c = 5;
int d = ++c; // c becomes 6 first, and then d gets 6
System.out.println(a + " " + b + " " + c + " " + d); // 6 5 6 6
As a rule, never use ++ or -- inside a bigger expression. The two forms look too much alike to read reliably, and the code is not shorter in a way that pays for the confusion. On its own as a whole statement, the line count++; is perfectly fine.
Which comparison operators exist?
There are six of them. They are ==, !=, <, >, <= and >=. Two rules about them catch people out.
String a = "hello";
String b = new String("hello");
System.out.println(a == b); // false, because they are two different objects
System.out.println(a.equals(b)); // true, because the text inside is the same
The first rule is that == on objects compares the references. Two strings that look the same but were built in different ways are not the same object, so use equals when you want to compare what is inside them.
The second rule is subtler. == on plain numbers compares the values, but when one side is a double the comparison is done in floating point, and that is why 0.1 + 0.2 == 0.3 is false. Comparing floating point numbers for equality needs a small tolerance.
What do the logical operators do?
The operators && and || join two booleans together, and they stop early. If the left-hand side already decides the answer, then the right-hand side is never evaluated at all. The operator ! reverses a boolean, and the operator ^ is exclusive-or.
String name = null;
if (name != null && !name.isEmpty()) {
System.out.println(name.length());
}
// the second test never runs, so this is safe
Stopping early is what makes the null check above safe. It is also the difference between a program that works and a program that crashes. The line a != null && a.length() > 0 works, while the line a.length() > 0 && a != null throws an error when a is null. The other forms, & and |, always evaluate both sides, so they are kept for flags.
What is the ternary operator?
The conditional operator takes three parts and gives you back one of two values. It is an expression, so you can use it in places where a statement would not work, such as inside a return, inside a list of arguments, or on the right-hand side of an assignment.
int age = 20;
String status = age >= 18 ? "adult" : "minor";
System.out.println(status);
System.out.println(age >= 18 ? "can vote" : "cannot vote");
Use it for a real either-or between two values. The moment it grows into nested ternaries, change it to an if statement. Nested ternaries are famously hard to read, and everybody who meets one wishes it had been written the other way.
What are the bitwise operators for?
They work on the individual bits inside a whole number. Most of the time you will not need them, but three uses come up often. You can test flags, you can shift bits, and you can take one part out of a value.
int flags = 0;
flags |= 1 << 0; // turn on bit 0
flags |= 1 << 2; // turn on bit 2
System.out.println(flags); // 5
System.out.println((flags & (1 << 0)) != 0); // true, because bit 0 is on
System.out.println((flags & (1 << 1)) != 0); // false
System.out.println(flags >> 1); // 2, which shifts right
System.out.println(-8 >>> 1); // 2147483644, which shifts right as unsigned
Bit flags are how a system that needs many separate booleans avoids a constructor with fifteen parameters. Shifts are how you multiply and divide by powers of two, and how you take the low bits off an identifier. The rest of the time, ordinary arithmetic and ordinary comparison are clearer.
What order do the operators apply in?
Java follows a fixed order of precedence, and it is worth learning the part that you use every day. Multiplication and division bind more tightly than addition and subtraction. Comparisons bind more tightly than the logical operators. And && binds more tightly than ||. Whenever the order is not obvious, the parentheses are not optional.
System.out.println(2 + 3 * 4); // 14
System.out.println((2 + 3) * 4); // 20
System.out.println(1 + 2 < 4 && 5 > 3); // true
System.out.println(true || false && false); // true, because && binds more tightly
Assignment sits below everything else, and it works from right to left, so the line a = b = c gives the value of c to b and then gives that result to a. The classic trap here is the missing brace. A for loop without braces only runs the first statement, so a line that you meant to be inside the loop does nothing at all.
Quick reference
- Whole number division cuts the remainder away, so widen the values first if you want a fraction.
- Compound assignment is shorter, and it checks for overflow at compile time.
- Never use ++ inside a bigger expression.
- == on objects compares the references, so use equals instead.
&&and || stop early, and that is what makes null checks safe.- The ternary operator is an expression, but nested ternaries make the code hard to read.
Try it yourself: write a program that reads a number and prints whether it is even, whether it is positive, and whether it divides evenly by three, using nothing but comparisons and logical operators. Then use bit flags to hold the three answers inside one whole number and print which flags are on. Finally, compare two strings that look the same with both == and equals, and explain the difference in one sentence.