Java's six relational operators, ==, !=, <, <=, > and >=, compare two values and give a boolean: true or false. To evaluate a condition, do the arithmetic first, then the comparison. For objects, == asks whether two references point to the same object, while equals asks whether two strings hold the same characters.
Quick check
In Java, what is 17 % 5, and what is 17 / 5?Show answerHide answer
17 % 5 is 2, the remainder, and 17 / 5 is 3, because
intdivision drops the remainder.What is the difference between x = 4 and x == 4?Show answerHide answer
x = 4stores 4 inx;x == 4asks whetherxalready equals 4 and givestrueorfalse.
Know these already? Jump to the practice questions
What you'll be able to do
- State the meaning of each of the six relational operators.
- Determine the value of a boolean expression for given values of its variables.
- Use the correct operator for a boundary such as "at least" or "more than".
- Explain the difference between
==andequalswhen comparing objects. - Identify comparisons that do not compile.
Key terms
Boolean expression
An expression whose value is true or false, such as age >= 16.
- In plain English
- A yes-or-no question the code asks.
- Don't write
- "
x >= 16returns 1 when it is true."
Relational operator
An operator that compares two values and gives a boolean: ==, !=, <, <=, > or >=.
- In plain English
- A comparison sign.
- Don't write
- "
=tests whether two values are equal."
Aliases
Two or more references that point to the same object.
- In plain English
- Two names for one thing.
- Don't write
- "
b = amakes a copy of the objectarefers to."
What do the six relational operators mean?
With int x = 7;:
| Operator | Meaning | Example | Value |
|---|---|---|---|
== | equal to | x == 7 | true |
!= | not equal to | x != 7 | false |
< | less than | x < 7 | false |
<= | less than or equal to | x <= 7 | true |
> | greater than | x > 5 | true |
>= | greater than or equal to | x >= 8 | false |
The two-character operators have no space and a fixed order: <=, not =<.
The four ordering operators (<, <=, >, >=) work only on numbers. == and != also work on boolean values and on references. When an int is compared with a double, the int is widened first, so 3 == 3.0 is true. Relational operators are Java syntax, not on the Java Quick Reference: Learn this.
Key idea
< and > leave out the boundary value; <= and >= include it.
Check yourself
Show answerHide answer
n > 10 is false and n >= 10 is true: only >= includes 10.
What can a boolean variable hold?
A boolean variable holds one of two values, true or false. You can store the result of a comparison in it and use it later:
int age = 15;
boolean canDrive = age >= 16;
System.out.println(canDrive);
This prints false, because 15 >= 16 is false. true and false are values, not strings, so they are written without quotes. When a boolean is printed or joined to a String, it shows as the word true or false.
Two boolean values can be compared with == or !=: canDrive == false is true here. They cannot be compared with < or >.
Check yourself
Show answerHide answer
true: 8 % 2 is 0, and 0 == 0 is true.
How do you evaluate a condition for given values?
Java follows a fixed order:
- Parentheses.
- Arithmetic:
*,/and%, then+and-. - The ordering operators
<,<=,>and>=. - The equality operators
==and!=.
So substitute the values, do all the arithmetic, then compare. With int a = 7; and int b = 2;:
| Expression | Arithmetic first | Value |
|---|---|---|
a / b * b == a | 3 * 2 is 6; 6 == 7 | false |
a % b != 0 | 1 != 0 | true |
a - b * 3 >= 1 | 7 - 6 is 1; 1 >= 1 | true |
Watch int division: a / b is 3, not 3.5, so a / b == 3.5 is false.
A chain such as 1 < x < 10 does not compile: 1 < x gives a boolean, and a boolean cannot be compared with <. Testing a range needs two comparisons joined, as the note on compound boolean expressions shows.
Check yourself
Show answerHide answer
false. p % 4 is 1, so the left side is 2; p / 2 is 4; and 2 > 4 is false.
What does == mean for objects?
A variable of a class type, such as String, holds a reference to an object. For references, == is true only when both point to the same object. equals compares what is inside: for String, the characters.
String a = new String("hi");
String b = new String("hi");
String c = a;
Each new creates a separate object, so a == b is false even though a.equals(b) is true. c = a copies the reference, not the object, so a and c are aliases and a == c is true.
Use equals to compare the contents of strings. Use == with objects only when you need to know whether two references point to the very same object, or whether a reference is null.
Check yourself
Show answerHide answer
Both are true: p and q are aliases of one object, which holds the same characters as itself.
Worked example 1: Evaluate three conditions
Question: What is printed?
int a = 9;
int b = 4;
double c = 2.25;
boolean p = a / b == c;
boolean q = a % b <= b - 3;
boolean r = (double) a / b >= c;
System.out.println(p + " " + q + " " + r);
What tells you the method
Each boolean comes from a comparison, so do the arithmetic, then compare, one line at a time.
Step 1: Trace each condition.
Variable Arithmetic Comparison Value p9 / 4 is 2 2 == 2.25 falseq9 % 4 is 1; 4 - 3 is 1 1 <= 1 truer9.0 / 4 is 2.25 2.25 >= 2.25 trueWhyIn
p, both operands of/areint, so the fraction is lost. Inr, the cast makesaadoublefirst, so the division keeps 2.25.Step 2: Join the results.
Each
booleanjoins to the spaces as a word.WhyA
+with aStringon either side joins.
Check it
q and r sit exactly on their boundaries (1 and 1; 2.25 and 2.25), and <= and >= include the boundary, so both are true.
Answer
false true true
Worked example 2: Compare references and contents
Question: What is printed?
String s1 = new String("go");
String s2 = new String("go");
String s3 = s1;
System.out.println(s1 == s2);
System.out.println(s1.equals(s2));
System.out.println(s1 == s3);
What tells you the method
== and equals are used on String variables, so track which object each variable refers to.
Step 1: Map the variables to objects.
Variable Refers to s1object 1, holding "go" s2object 2, holding "go" s3object 1 WhyEach
newmakes a separate object;s3 = s1copies the reference.Step 2: Evaluate each line.
s1 == s2compares objects 1 and 2:false.s1.equals(s2)compares characters:true.s1 == s3compares object 1 with itself:true.Why==checks for the same object;equalschecks for the same characters.
Check it
s3.equals(s2) would also be true, because object 1 and object 2 hold the same characters.
Answer
false then true then true, each on its own line.
Worked example 3: Choose the boundary
Question: A method should return true when count is at least limit. Which return statement does this?
- A)
return count > limit; - B)
return limit >= count; - C)
return count => limit; - D)
return count >= limit;
What tells you the method
"At least" names a boundary, so test each option at the boundary and just below it.
Step 1: Pick test values.
Use
limit= 5 withcount= 5 (should givetrue) andcount= 4 (should givefalse).WhyBoundary errors show up only at the boundary.
Step 2: Test each option.
A gives
falsefor 5, so it leaves out the boundary. B givestruefor 5 (5 >= 5) but alsotruefor 4 (5 >= 4): its comparison faces the wrong way. C does not compile, because=>is not a Java operator. D givestruefor 5 andfalsefor 4.WhyOnly D includes 5 and excludes 4.
Check it
D with count = 6 gives 6 >= 5, true, which is right for "at least".
Answer
D
Your turn
Question: What is printed?
int n = -7;
boolean a = n % 2 == 1;
boolean b = n % 2 != 0;
System.out.println(a + " " + b);
Step 1: Work out the remainder.
In Java,
%gives a result with the sign of the left operand, so -7 % 2 is -1.Step 2: Your go: compare -1 with 1 and with 0, then build the printed line.
Show the full solutionHide the solution
Step 2. -1 == 1 is false, so a is false. -1 != 0 is true, so b is true. The line joins them with a space.
Answer: false true
Traps
Trap
Two strings with the same characters always give true with ==.
It seems right because == gives true for equal int values. But for objects, == compares references, so two separate objects with the same characters give false. Use equals to compare contents.
Which expression is certain to be true after String u = new String("ab"); String v = new String("ab");: u == v or u.equals(v)?
u.equals(v). u == v is false, because u and v refer to different objects.
Trap
> and >= mean the same thing for whole numbers.
It seems right because they agree for most values. But they differ exactly at the boundary: 70 > 70 is false and 70 >= 70 is true. Test the boundary value every time.
For int score = 70; which is true: score > 70 or score >= 70?
score >= 70.
What's examined
On the AP® Computer Science A exam (Unit 2), multiple-choice questions ask you to evaluate conditions for given values, spot boundary errors and choose between == and equals. Free-response methods use these comparisons in the conditions of if statements and loops. equals is on the Java Quick Reference; the operators are not.
Practice questions
- Recall With
int x = 3;declared, which expression has typeboolean?
- A)
x = 5 - B)
x + 5 - C)
x >= 5 - D)
"x" + 5
Show answer
Answer: C. A relational operator always gives a boolean.
Why the others are wrong:
- A is an assignment, whose value is the
int5. - B is an
intsum. - D joins to the
String"x5".
- Apply What is printed?
int x = 12;
int y = 5;
System.out.println(x / y >= 2);
System.out.println(x % y == y - 3);
System.out.println(x * 1.0 / y != 2.4);
Show answer
Answer: true then true then false, each on its own line.
Marking points:
- 12 / 5 is 2, and 2 >= 2 is
true. - 12 % 5 is 2 and 5 - 3 is 2, so
==givestrue. x * 1.0is 12.0, so the division gives 2.4, and 2.4 != 2.4 isfalse.
- Apply After this code segment runs, which expression evaluates to
false?
String a = new String("hi");
String b = a;
String c = new String("hi");
- A)
a == c - B)
a == b - C)
a.equals(c) - D)
b.equals(c)
Show answer
Answer: A. a and c refer to two separate objects, so == gives false.
Why the others are wrong:
- B:
aandbare aliases of one object, so==givestrue. - C:
aandcare different objects holding the same characters, "hi", soequalsgivestrue. - D:
brefers to the same object asa, sob.equals(c)givestruefor the same reason as C.
- Exam-style The method should return
truewhenscoreis 70 or more. Give the number of the line that stops it working.
1: public static boolean isPassing(int score)
2: {
3: boolean pass = score > 70;
4: return pass;
5: }
Show answer
Answer: Line 3.
Marking points:
isPassing(70)returnsfalse, because 70 > 70 isfalse.- The fix is
boolean pass = score >= 70;.
- Exam-style Which statement does not compile?
- A)
boolean t = 5 > 3; - B)
boolean u = 1 < 2 < 3; - C)
boolean v = true == false; - D)
boolean w = 2.5 != 2;
Show answer
Answer: B. 1 < 2 gives a boolean, and a boolean cannot be compared with <.
Why the others are wrong:
- A compares two numbers, which is allowed.
- C:
==can compare twobooleanvalues; the result isfalse. - D: the
int2 is widened to 2.0, and 2.5 != 2.0 istrue.
- Apply What is printed?
boolean done = false;
int tries = 3;
boolean more = tries < 5;
done = tries * 2 == 6;
System.out.println(done + " " + more + " " + (done != more));
Show answer
Answer: true true false
Marking points:
moreis 3 < 5, which istrue;doneis reassigned 6 == 6, which istrue.done != morecomparestruewithtrue, givingfalse.
- Recall Name the Java primitive type whose only values are
trueandfalse.
Show answer
Answer: boolean
Marking points:
- Every relational operator gives a value of this type.
Key points
Recall, then reveal
Say the main points from memory first, then check them.
Show key pointsHide key points
- The six relational operators each give a
boolean. - Do the arithmetic before the comparison, and watch
intdivision and%. <and>exclude the boundary;<=and>=include it.- Ordering operators work only on numbers;
==and!=also work on booleans and references. - For objects,
==means the same object;equalsmeans the same characters.