[!NOTE] Operators are the symbols that perform operations on variables and values. You will need to chain these together frequently to create robust boolean conditions.
The 4 Categories of Operators
| Category | Purpose | Examples |
|---|---|---|
| Arithmetic | Math calculations | +, -, *, /, % (Modulo) |
| Assignment | Setting variable values | =, +=, -= |
| Comparison | Evaluating equality | ==, !=, >, <= |
| Logical | Chaining boolean logic | && (AND), ` |
The Modulo Operator (%)
While / gives you the quotient of division, % gives you the Remainder of division. This is extremely useful for determining if a number is Even or Odd!
int remainder = 10 % 3; // Returns 1 (because 10 divided by 3 is 9, remainder 1).
if (number % 2 == 0) {
System.out.println("This number is definitely EVEN.");
}
Logical Short-Circuit Evaluation
Logical operators (&& and ||) possess an intelligent "short-circuit" mechanism to speed up code execution and prevent Null Pointer Exceptions.
If the first condition in an && (AND) statement evaluates to false, Java realizes that the entire condition is doomed to fail. Therefore, it will not even bother evaluating the second condition.
Similarly, if the first condition in an || (OR) statement evaluates to true, Java will not evaluate the second condition, because the overall result is guaranteed to be true.
// Safe Execution Example!
// If 'user' is null, the first check fails.
// Because of the && short-circuit, Java STOPS evaluating.
// It never attempts to run user.isActive(), preventing an app crash!
if (user != null && user.isActive() == true) {
System.out.println("User is logged in safely.");
}
[!CAUTION] If you actually want both sides to evaluate no matter what, use the bitwise
&and|operators instead. But this is extremely rare in web applications.