Big idea: A Boolean expression is a question with a true/false answer, such as "is x greater than 10?". Relational operators build them.
Learning objectives
Develop code to create Boolean expressions with relational operators and determine the result of these expressions.
Relational operators
Operator
Meaning
Example (x is 7)
Result
==
equal to
x == 7
true
!=
not equal to
x != 7
false
<
less than
x < 7
false
<=
less than or equal
x <= 7
true
>
greater than
x > 3
true
>=
greater than or equal
x >= 8
false
Code
int x = 7;
boolean big = x > 5;
System.out.println(big);
System.out.println(x % 2 == 0);
System.out.println(x / 2 == 3);
Output
true
false
true
Comparing primitives vs. references
For primitives, == compares values. For references, == asks whether both variables refer to the same object. That's why Strings and other objects should be compared with equals.
Code
String a = newString("hi");
String b = newString("hi");
String c = a;
System.out.println(a == b);
System.out.println(a == c);
System.out.println(a.equals(b));
Output
false
true
true
Key points
Relational operators: == != < <= > >=. Each produces a boolean.
== on primitives compares values; on references it compares object references.
Watch out
= assigns; == compares.
== on two String objects checks whether they are the same object, not the same text.