Sub topic 5
Operators and Expressions
Prerequisites and What This Chapter Covers
This chapter is written for beginners. Before you start, you should have read the earlier chapters on how Java runs and on variables and types. You do not need to be an expert: we will explain every term the first time it appears. If you have not yet run a Java program on your machine, it helps to have the JDK (Java Development Kit, the free software that compiles and runs Java) installed so you can try the examples.
An operator is a symbol that performs an action on one or more values. An expression is a combination of values, variables, and operators that produces a new value. For example, 2 + 3 is an expression that uses the + operator and produces the value 5.
Operators matter because almost every program needs them: comparing a password, adding up a shopping cart, or deciding if a game is over. This chapter walks through the main operator groups in Java, with runnable examples and the common beginner mistakes.
Arithmetic Operators
Arithmetic operators do math on numbers.
| Operator | Name | Example | Result |
|---|---|---|---|
| `+` | Addition | `7 + 2` | `9` |
| `-` | Subtraction | `7 - 2` | `5` |
| `*` | Multiplication | `7 * 2` | `14` |
| `/` | Division | `7 / 2` | `3` |
| `%` | Remainder (modulo) | `7 % 2` | `1` |
The / and % rows deserve attention. When you divide two whole numbers (int values, which store numbers without a decimal point), Java throws away the fraction: 7 / 2 is 3, not 3.5. The % operator gives you the leftover: 7 % 2 is 1.
public class MathDemo {
public static void main(String[] args) {
int totalSeconds = 130;
int minutes = totalSeconds / 60; // 2
int seconds = totalSeconds % 60; // 10
System.out.println(minutes + " min " + seconds + " sec");
double precise = 7.0 / 2; // 3.5
System.out.println(precise);
}
}If at least one operand (a value the operator works on) is a double (a number with a decimal point), Java uses floating-point division and keeps the fraction.
Increment and Decrement
Java has shortcuts for adding or subtracting one: ++ and --.
int count = 0;
count++; // count is now 1
count--; // count is back to 0These operators come in two flavors. Prefix means the operator goes before the variable (++count): the value changes first, then the new value is used. Postfix means it goes after (count++): the old value is used, then the value changes. In practice, most code uses count++ on its own line, where the difference does not matter.
Assignment Operators
The = operator assigns a value: it stores the right-hand value into the variable on the left. Note that = is not "equals" in the math sense; it is "becomes."
int score = 0; // score becomes 0
score = score + 10; // score becomes 10Because x = x + 10 is so common, Java offers compound assignment operators that combine an operation with assignment.
| Operator | Meaning | Example |
|---|---|---|
| `+=` | add and assign | `score += 10` means `score = score + 10` |
| `-=` | subtract and assign | `score -= 5` |
| `*=` | multiply and assign | `score *= 2` |
| `/=` | divide and assign | `score /= 2` |
| `%=` | remainder and assign | `score %= 3` |
One subtle rule: a compound operator includes an automatic cast (a conversion from one type to another). byte b = 1; b += 1; works even though b = b + 1 would not compile, because += quietly converts the result back to byte.
Comparison Operators
Comparison operators compare two values and produce a boolean, a type with only two values: true or false.
| Operator | Question it asks | Example | Result |
|---|---|---|---|
| `==` | equal? | `5 == 5` | `true` |
| `!=` | not equal? | `5 != 3` | `true` |
| `<` | less than? | `4 < 3` | `false` |
| `>` | greater than? | `4 > 3` | `true` |
| `<=` | less than or equal? | `3 <= 3` | `true` |
| `>=` | greater than or equal? | `2 >= 3` | `false` |
The single most common beginner mistake in Java is using = (assignment) where == (comparison) is meant. if (x = 5) will not even compile in Java when x is an int, which saves you, but the habit still causes errors with other types.
Logical Operators
Logical operators combine boolean values.
| Operator | Name | True when... | Column | Column |
|---|---|---|---|---|
| `&&` | AND | both sides are true | ||
| `\ | \ | ` | OR | at least one side is true |
| `!` | NOT (reverses) | the value is false |
int age = 25;
boolean hasTicket = true;
boolean canEnter = age >= 18 && hasTicket; // true && true -> true
boolean isChild = !(age >= 18); // !true -> falseJava's && and || use short-circuit evaluation: Java evaluates the left side first, and if the answer is already decided, it skips the right side. For &&, a false on the left means the whole expression is false no matter what, so the right side never runs. This is useful and safe:
int[] nums = {1, 2, 3};
if (nums.length > 3 && nums[3] > 0) { // right side never runs
System.out.println("safe");
}Here nums[3] would crash (the array has indexes 0 to 2), but the left side is already false, so Java never evaluates the right side.
Operator Precedence
Precedence is the rule for which operator acts first when several appear in one expression. Multiplication binds tighter than addition, so 2 + 3 * 4 is 14, not 20. Comparisons bind tighter than && and ||.
You can always override precedence with parentheses. Good style is to add parentheses even when they are not required, because they make your intent clear to readers.
flowchart TD
A["2 + 3 * 4 > 9 && true"] --> B["3 * 4"]
B --> C["2 + 12"]
C --> D["14 > 9"]
D --> E["true && true"]
E --> F["true"]caption: How Java evaluates a mixed expression, innermost operations first alt: A flowchart starting from the full expression, showing multiplication first, then addition, then the comparison, then the logical AND, ending with the value true.
String Concatenation: When Plus Is Not Math
When either side of + is a String (a piece of text), Java joins the values instead of adding them. This is called concatenation.
System.out.println("Total: " + 3 + 4); // prints: Total: 34
System.out.println("Total: " + (3 + 4)); // prints: Total: 7Java works left to right: "Total: " + 3 makes the text "Total: 3", then + 4 appends again, giving 34. Parentheses force the math first.
callout note The plus operator has two personalities: arithmetic for numbers, joining for text. When you see unexpected output like Total: 34, look for a string on the left side of a +.
A Worked Example: Grade Calculator
The following program puts everything together: arithmetic, comparison, logical operators, and precedence.
public class GradeCalc {
public static void main(String[] args) {
int midterm = 82;
int finalExam = 90;
int homework = 95;
// weighted average: 40% midterm, 40% final, 20% homework
double average = midterm * 0.4 + finalExam * 0.4 + homework * 0.2;
boolean passed = average >= 60;
boolean honorRoll = average >= 90 && homework >= 90;
System.out.println("Average: " + average);
System.out.println("Passed: " + passed);
System.out.println("Honor roll: " + honorRoll);
// parity check with remainder
System.out.println("Even score? " + (midterm % 2 == 0));
}
}Run it and you should see the average 88.0, Passed: true, Honor roll: false, and Even score? true. Trace through each line and predict the output before running; that habit is how expressions become second nature.
flowchart TD
S["Inputs: three scores"] --> W["Weighted average expression"]
W --> P1["Compare: average >= 60"]
W --> P2["Compare and combine: average >= 90 && homework >= 90"]
W --> P3["Remainder: midterm % 2 == 0"]
P1 --> R["Booleans printed"]
P2 --> R
P3 --> Rcaption: Data flow in the grade calculator, from raw scores to printed booleans alt: A flowchart showing three input scores flowing into a weighted average calculation, which then feeds three separate boolean expressions whose results are printed.
Common Errors to Avoid
- Using
=instead of==in comparisons. Read==aloud as "is equal to" and=as "becomes." - Expecting
7 / 2to be3.5. Whole-number division drops the fraction; use adoubleoperand if you need it. - Forgetting that
%can be negative:-7 % 2is-1in Java, not1. - Writing
"Total: " + 3 + 4and expecting7. Parenthesize the math. - Mixing
&and|(bitwise, non-short-circuit versions) with&&and||. The single-character versions evaluate both sides always and are rarely what beginners want.
exercise Q: What does System.out.println(9 % 4 + " apples " + 2 + 2); print? A: It prints 1 apples 22. First, 9 % 4 is evaluated to 1. Then 1 + " apples " concatenates to the text 1 apples . Finally + 2 + 2 appends each number as text, giving 1 apples 22.
exercise Q: Write a boolean expression that is true when a variable n is between 1 and 100 (inclusive). A: n >= 1 && n <= 100. The two comparisons each produce a boolean, and && is true only when both hold.
exercise Q: Why is average = midterm * 0.4 + finalExam * 0.4 + homework * 0.2 safe without parentheses around each multiplication? A: * has higher precedence than +, so each multiplication happens before the additions, exactly as intended.
estimate minutes: 75