Java for Beginners · Module 3: Operators
🎯 Asking Questions in Code
Programs need to make decisions: is the student’s mark above 40? Is the user’s age between 18 and 25? Relational operators compare two values, and logical operators combine the answers. Both give a boolean result, true or false, which later drives if statements and loops.
1️⃣ Relational Operators
| Operator | Meaning | Example (a = 12, b = 20) | Result |
== | equal to | a == b | false |
!= | not equal to | a != b | true |
< | less than | a < b | true |
> | greater than | a > b | false |
<= | less than or equal | a <= 12 | true |
>= | greater than or equal | b >= 25 | false |
Figure 1: Relational operators compare two values.
Program 1: Comparing values
public class RelDemo {
public static void main(String[] args) {
int a = 12, b = 20;
System.out.println("a == b : " + (a == b));
System.out.println("a != b : " + (a != b));
System.out.println("a < b : " + (a < b));
System.out.println("a > b : " + (a > b));
System.out.println("a <= 12: " + (a <= 12));
System.out.println("b >= 25: " + (b >= 25));
System.out.println("'a' < 'b': " + ('a' < 'b'));
System.out.println("0.1+0.2 == 0.3 : " + (0.1 + 0.2 == 0.3));
System.out.println("close enough : " + (Math.abs(0.1 + 0.2 - 0.3) < 1e-9));
}
}
a == b : false
a != b : true
a < b : true
a > b : false
a <= 12: true
b >= 25: false
‘a’ < ‘b’: true
0.1+0.2 == 0.3 : false
close enough : true
==tests equality. A single=is assignment, which is a very different thing.- Characters compare by their codes, so
'a' < 'b'is true. - Do not compare decimals with
==. Because 0.1 + 0.2 is stored as 0.30000000000000004 (Lesson 8), the test is false. Instead check that the difference is very small, as the last line does withMath.abs.
2️⃣ Logical Operators
| A | B | A && B (AND) | A || B (OR) | !A (NOT) |
| true | true | true | true | false |
| true | false | false | true | false |
| false | true | false | true | true |
| false | false | false | false | true |
Figure 2: Truth table for the logical operators.
Program 2: Combining conditions
public class LogicDemo {
public static void main(String[] args) {
int marks = 72;
int attendance = 80;
boolean passed = marks >= 40;
boolean eligible = attendance >= 75;
System.out.println("passed && eligible : " + (passed && eligible));
System.out.println("passed || eligible : " + (passed || eligible));
System.out.println("!passed : " + (!passed));
boolean distinction = marks >= 75 && attendance >= 75;
System.out.println("distinction : " + distinction);
int age = 19;
boolean student = age >= 18 && age <= 25;
System.out.println("age in 18..25 : " + student);
}
}
passed && eligible : true
passed || eligible : true
!passed : false
distinction : false
age in 18..25 : true
- You can store the result of a comparison in a
booleanvariable and reuse it. distinctionis false because the marks (72) fail the first test, even though attendance passes.- To check a range, write both comparisons and join them with
&&:age >= 18 && age <= 25.
3️⃣ Short-Circuit Evaluation
A && Bresult is already false
A || Bresult is already true
Figure 3: Short-circuit evaluation: Java stops as soon as the answer is certain.
With && and ||, Java stops evaluating as soon as the answer is certain. The single-character versions & and | always evaluate both sides.
public class ShortCircuit {
static boolean check(String name, boolean value) {
System.out.println(" checking " + name);
return value;
}
public static void main(String[] args) {
System.out.println("Using && :");
boolean r1 = check("A", false) && check("B", true);
System.out.println(" result = " + r1);
System.out.println("Using & :");
boolean r2 = check("A", false) & check("B", true);
System.out.println(" result = " + r2);
System.out.println("Using || :");
boolean r3 = check("A", true) || check("B", false);
System.out.println(" result = " + r3);
int x = 0;
if (x != 0 && 10 / x > 1) {
System.out.println("big");
} else {
System.out.println("safe: division skipped");
}
}
}
Using && :
checking A
result = false
Using & :
checking A
checking B
result = false
Using || :
checking A
result = true
safe: division skipped
- With
&&, A is false, so B is never checked. With&, both are checked. - With
||, A is true, so B is skipped. - The last block shows why short-circuiting is useful: since
x != 0is false,10 / xnever runs, so there is no divide-by-zero error. - The
checkmethod here is a small helper that prints a message and returns the value. Methods are covered in Lesson 25.
4️⃣ == Compares References for Objects
For primitives, == compares values. For objects such as String, == asks whether both names point to the same object. To compare the contents, use equals().
public class EqualsTrap {
public static void main(String[] args) {
String s1 = new String("java");
String s2 = new String("java");
System.out.println("s1 == s2 : " + (s1 == s2));
System.out.println("s1.equals(s2) : " + s1.equals(s2));
}
}
s1 == s2 : false
s1.equals(s2) : true
- Two separate objects hold the same text, so
==is false andequals()is true. Lesson 23 explains this fully.
5️⃣ Errors Beginners Meet
Assignment instead of comparison
public class Bad1 {
public static void main(String[] args) {
int a = 5;
if (a = 5) {
System.out.println("five");
}
}
}
Bad1.java:4: error: incompatible types: int cannot be converted to boolean
if (a = 5) {
^
1 error
a = 5assigns and produces an int, not a boolean. Writea == 5. (In Java this mistake is caught by the compiler. In C it would compile silently.)
Chaining comparisons like in maths
public class Bad2 {
public static void main(String[] args) {
int x = 15;
boolean ok = 10 < x < 20;
System.out.println(ok);
}
}
Bad2.java:4: error: bad operand types for binary operator ‘<‘
boolean ok = 10 < x < 20;
^
first type: boolean
second type: int
1 error
10 < xbecomes a boolean, which cannot be compared to 20. Write10 < x && x < 20.
⚠️ Common Mistakes
| Mistake | Problem | Fix |
|---|---|---|
Using = to compare | Assignment, not comparison | Use == |
10 < x < 20 | Not allowed in Java | 10 < x && x < 20 |
Comparing Strings with == | Compares references | Use equals() |
Comparing doubles with == | Tiny rounding errors | Compare with a tolerance |
Using & when you meant && | No short-circuit | Use && for conditions |
Writing =< or => | Wrong order | Write <= and >= |
❓ Frequently Asked Questions
Q1. What is the difference between = and ==?= stores a value in a variable. == checks whether two values are equal.
Q2. Can I compare a boolean with ==?
Yes, but it is simpler to write if (done) than if (done == true).
Q3. Which has higher priority, && or ||?&& binds tighter than ||. When in doubt, add brackets. Lesson 15 gives the full order.
Q4. Why is short-circuiting useful?
It avoids errors (like dividing by zero) and saves time by skipping unnecessary checks.
✅ Key Takeaways
- Relational operators (
== != < > <= >=) always give true or false. - Logical operators combine conditions:
&&(both),||(either),!(flip). &&and||short-circuit: the second part is skipped when the answer is already known.- Use
equals()for Strings and a tolerance for decimals. - Check a range with two comparisons:
x >= 10 && x <= 20.
🎓 Practice questions: (1) Write a boolean expression that is true if a year is a leap year. (2) What does!(5 > 3 && 2 > 4)give? (3) Why does0.1 + 0.2 == 0.3give false? (4) Explain how short-circuiting prevents a crash inx != 0 && 10 / x > 1. (5) Write a condition that checks whether a character is an uppercase letter.
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