Java for Beginners · Module 3: Operators
🎯 The Last Piece of the Operator Puzzle
You now know the arithmetic, comparison, logical and bitwise operators. This lesson covers three more things: the assignment operator, the ternary operator (a one-line if-else) and precedence, which decides which operator runs first when a line has several.
1️⃣ The Assignment Operator =
= copies the value on the right into the variable on the left. It is evaluated right to left, so you can chain it.
public class AssignDemo {
public static void main(String[] args) {
int a, b, c;
a = b = c = 7;
System.out.println("a = " + a + ", b = " + b + ", c = " + c);
int x = 10;
int y = x;
x = 99;
System.out.println("x = " + x + ", y = " + y);
int total = 0;
total += 5;
total += 7;
System.out.println("total = " + total);
}
}
a = 7, b = 7, c = 7
x = 99, y = 10
total = 12
a = b = c = 7works from the right: c gets 7, then b gets the value of that, then a.y = xcopies the value. Later changingxdoes not changey.- The left side of
=must be a variable. Compound forms like+=were covered in Lesson 12.
2️⃣ The Ternary Operator ? :
(marks >= 40)condition
"Pass"if true
"Fail"if false
condition ? valueIfTrue : valueIfFalse. It is the only operator in Java with three operands, so it is called the ternary operator.Figure 1: The conditional (ternary) operator.
Program 2: Choosing a value in one line
public class TernaryDemo {
public static void main(String[] args) {
int marks = 62;
String result = (marks >= 40) ? "Pass" : "Fail";
System.out.println("Result: " + result);
int a = 14, b = 29;
int max = (a > b) ? a : b;
System.out.println("Max = " + max);
int n = 7;
System.out.println(n + " is " + (n % 2 == 0 ? "even" : "odd"));
int score = 85;
String grade = score >= 90 ? "A" : score >= 75 ? "B" : score >= 50 ? "C" : "D";
System.out.println("Grade: " + grade);
}
}
Result: Pass
Max = 29
7 is odd
Grade: B
- The test runs first. If it is true, the value before the colon is the answer. Otherwise the value after it is.
- It produces a value, so you can store it in a variable or use it inside
println. - Ternaries can be nested, as in the grade example. Beyond two levels they become hard to read, so use
if-else(Lesson 16) instead. - Both possible results must have compatible types.
3️⃣ Operator Precedence and Associativity
In 2 + 3 * 4, does Java add first or multiply first? Precedence is the priority order of operators. Higher priority runs first. When two operators have the same priority, associativity decides: most go left to right.
2 + 3 * 42 + 12(2 + 3) * 45 * 4Figure 3: Precedence decides the order. Brackets override it.
| Priority | Operators | Direction |
| 1 (highest) | () brackets, x++ x-- | left to right |
| 2 | ++x --x ! ~ unary + - | right to left |
| 3 | * / % | left to right |
| 4 | + - | left to right |
| 5 | << >> >>> | left to right |
| 6 | < <= > >= | left to right |
| 7 | == != | left to right |
| 8 | & | left to right |
| 9 | ^ | left to right |
| 10 | | | left to right |
| 11 | && | left to right |
| 12 | || | left to right |
| 13 | ? : | right to left |
| 14 (lowest) | = += -= *= and other assignments | right to left |
Figure 2: Operator precedence, from highest to lowest priority.
Program 3: Precedence at work
public class Precedence {
public static void main(String[] args) {
System.out.println("2 + 3 * 4 = " + (2 + 3 * 4));
System.out.println("(2 + 3) * 4 = " + ((2 + 3) * 4));
System.out.println("20 - 6 - 3 = " + (20 - 6 - 3));
System.out.println("100 / 10 * 2 = " + (100 / 10 * 2));
System.out.println("10 + 5 % 3 = " + (10 + 5 % 3));
System.out.println("1 + 2 + \"3\" = " + (1 + 2 + "3"));
boolean r = true || false && false;
System.out.println("true || false && false = " + r);
boolean r2 = (true || false) && false;
System.out.println("(true || false) && false = " + r2);
int a = 5;
int b = a++ * 2 + 3;
System.out.println("a++ * 2 + 3 with a=5 -> b = " + b + ", a = " + a);
int p, q;
p = q = 4 + 2 * 3;
System.out.println("p = q = 4 + 2 * 3 -> " + p + ", " + q);
}
}
2 + 3 * 4 = 14
(2 + 3) * 4 = 20
20 – 6 – 3 = 11
100 / 10 * 2 = 20
10 + 5 % 3 = 12
1 + 2 + “3” = 33
true || false && false = true
(true || false) && false = false
a++ * 2 + 3 with a=5 -> b = 13, a = 6
p = q = 4 + 2 * 3 -> 10, 10
*beats+, so 2 + 3 * 4 is 14. Brackets change the order and give 20.- Same priority goes left to right:
20 - 6 - 3is (20 – 6) – 3 = 11, and100 / 10 * 2is (100 / 10) * 2 = 20. %has the same priority as*, higher than+: 10 + (5 % 3) = 12.1 + 2 + "3"adds the numbers first (3), then joins the text, giving “33”.&&beats||, sotrue || false && falseistrue || (false && false), which is true.a++ * 2 + 3uses the old a (5): 5 × 2 + 3 = 13, and then a becomes 6.- Assignment has the lowest priority and goes right to left, so the whole right side is calculated before it is stored.
4️⃣ Errors Beginners Meet
Mismatched types in a ternary
public class Bad1 {
public static void main(String[] args) {
int a = 3, b = 8;
int max = (a > b) ? "a" : b;
System.out.println(max);
}
}
Bad1.java:4: error: incompatible types: bad type in conditional expression
int max = (a > b) ? “a” : b;
^
String cannot be converted to int
1 error
- The result must fit the variable, so both choices must be ints here.
Assigning to a value
public class Bad2 {
public static void main(String[] args) {
int x = 5;
10 = x;
System.out.println(x);
}
}
Bad2.java:4: error: unexpected type
10 = x;
^
required: variable
found: value
1 error
- The variable goes on the left and the value on the right:
x = 10;.
⚠️ Common Mistakes
| Mistake | Problem | Fix |
|---|---|---|
Assuming a + b * c adds first | * is higher priority | Use brackets (a + b) * c |
| Long nested ternaries | Unreadable | Use if-else |
| Different types in the two ternary results | Compile error or surprise conversion | Keep both the same type |
5 = x | Left side is not a variable | x = 5 |
Writing 1 + 2 + "3" expecting “123” | Numbers are added first | Start with a String: "" + 1 + 2 + 3 |
❓ Frequently Asked Questions
Q1. Is the ternary operator better than if-else?
It is shorter for choosing one of two values. For anything with several statements, if-else is clearer.
Q2. What does associativity mean?
It is the direction used when operators have the same priority. Most go left to right. Assignment and the ternary go right to left.
Q3. Do brackets slow the program down?
No. Brackets only affect how the compiler reads the expression.
Q4. Is = an operator?
Yes. It produces a value too, which is why a = b = 5 works.
✅ Key Takeaways
=stores the right-hand value in the left-hand variable, and chains from right to left.condition ? A : Bis a one-line choice between two values.- Order of work: brackets, then
* / %, then+ -, then comparisons, then&&, then||, then assignment. - Same-priority operators usually run left to right.
- Use brackets whenever the order is not obvious.
🔁 Module 3 Recap
Lessons 12 to 15 covered arithmetic, relational, logical, bitwise, shift, assignment and ternary operators. With these you can write any expression, and next you will use them to make decisions with if and switch in Module 4.
🎓 Practice questions: (1) Predict, then check:int r = 10 + 20 / 5 * 2 - 3;(2) Use the ternary operator to find the largest of three numbers. (3) What is the value of5 > 3 && 2 > 4 || 1 < 2? (4) Rewritea + b * c - d / ewith brackets that show the actual order. (5) What does"" + 1 + 2 + 3print, and why?
All 30 lessons in this series (open course page)
Module 1 · Getting Started
- Lesson 1: What is Java? Features and Uses
- Lesson 2: Installing the JDK and Running Your First Program
- Lesson 3: JDK, JRE, JVM and WORA Explained
- Lesson 4: JVM Architecture and JIT Compilation
- Lesson 5: Hello World Program Explained Line by Line
Module 2 · Building Blocks
- Lesson 6: Comments, Identifiers and Keywords
- Lesson 7: Variables and Literals
- Lesson 8: Primitive Data Types in Java
- Lesson 9: Type Conversion and Casting
- Lesson 10: Taking Input with the Scanner Class
- Lesson 11: Escape Characters and Variable Scope in Java
Module 3 · Operators
- Lesson 12: Arithmetic Operators and Increment/Decrement in Java
- Lesson 13: Relational and Logical Operators in Java
- Lesson 14: Bitwise and Shift Operators in Java
- Lesson 15: Assignment, Ternary Operator and Operator Precedence in Java
Module 4 · Control Flow
- Lesson 16: if, if-else and else-if Ladder in Java
- Lesson 17: switch Statement in Java (Classic and Modern)
- Lesson 18: while and do-while Loops in Java
- Lesson 19: for Loop and Nested Loops (Patterns) in Java
- Lesson 20: break, continue and Labelled Loops in Java
Module 5 · Data and Methods
- Lesson 21: Arrays in Java (One-Dimensional)
- Lesson 22: Multidimensional Arrays in Java
- Lesson 23: Strings and the String Pool in Java
- Lesson 24: String Methods and StringBuilder in Java
- Lesson 25: Methods and Method Overloading in Java
- Lesson 26: Recursion Basics in Java
- Lesson 27: ArrayList and Wrapper Classes in Java
- Lesson 28: Exception Handling Basics in Java