Comparisons and logic
What you'll learn:
- compare values and combine conditions with
&&,||and!; - choose which code runs with
if,elseand the?:operator; - write a classic
switchand explain why it needsbreak; - get a value out of an arrow
switch.
Picture a fork in the road with a signpost: "Left if you are under 18, right for everyone else." To pick a road, you answer the signpost's question. There are only two answers: yes or no.
A program makes choices all the time too: let a user in or not, print one message or another. For that it needs questions with a yes-or-no answer. In Java such an answer is a value of type boolean: true or false. You have already met this type among the eight primitive ones. You ask a program a question with a comparison:
public class Main {
public static void main(String[] args) {
int age = 17;
boolean adult = age >= 18;
System.out.println(adult); // false
System.out.println(age == 17); // true
System.out.println(age != 17); // false
}
}Let's walk through the program line by line:
int age = 17;sets up a variable with the age.age >= 18asks, "Isagegreater than or equal to 18?" The answer,false, goes into thebooleanvariableadult.System.out.println(adult)printsfalse.age == 17asks whetherageequals 17 and givestrue.age != 17asks the opposite and givesfalse.
Comparison operators
Comparison operators compare two values and give a boolean. Java has six of them:
| Operator | What it asks | Example |
|---|---|---|
== | are the values equal | 5 == 5 gives true |
!= | are the values different | 5 != 5 gives false |
< | is the left one smaller | 3 < 5 gives true |
<= | smaller or equal | 5 <= 5 gives true |
> | is the left one greater | 3 > 5 gives false |
>= | greater or equal | 3 >= 5 gives false |
A check for equality takes two signs: ==. A single = is assignment: it puts a value into a variable instead of asking a question.
Logical operators
A signpost can also ask a compound question: "Left if it is raining and you have no umbrella." Such a question is built from two simple ones. Logical operators combine several boolean answers into one:
int age = 25;
boolean hasTicket = false;
System.out.println(age >= 18 && hasTicket); // false
System.out.println(age >= 18 || hasTicket); // true
System.out.println(!hasTicket); // trueAND: &&
a && b gives true only when both sides are true. In the example the age fits but there is no ticket, so the result is false.
OR: ||
a || b gives true when at least one side is true. The age fits, and that is enough for true. The result is false only when both sides are false.
NOT: !
The ! operator goes in front of a single value and turns the answer into its opposite: !false is true. It reads as "not": !hasTicket means "no ticket".
&& binds tighter than ||, the way multiplication binds tighter than addition. When a condition has both, add parentheses: (a || b) && c reads without guesswork.
Short-circuit evaluation
Java evaluates && and || from left to right and stops as soon as the answer is known. If the left side of && is false, the whole answer is already false, and Java does not evaluate the right side. || does the same when its left side is true: the answer is already true. This behavior is called short-circuit evaluation.
The fork works the same way. If the answer to "Is it raining?" is "no", there is no point asking about the umbrella:
int x = 0;
System.out.println(x != 0 && 10 / x > 1); // falseLet's see what happens here:
x != 0givesfalse.- The left side of
&&is false, so Java does not evaluate10 / x > 1. - No division by zero happens, and the program prints
false.
Dividing an integer by zero throws an ArithmeticException and stops the program. Here the division is never reached. The left side works as a guard: it lets only a nonzero x through to the division.
Interviewers often ask what short-circuit evaluation is and why the zero check goes on the left.
Only boolean
Here the signpost and Java part ways. A person can answer "I don't know" or "probably yes". Java has no third answer: where an answer is needed, only a boolean fits. A number does not count as an answer, although in some languages zero means "no".
So the compiler rejects these when x is an int:
boolean ok = x;fails withincompatible types: int cannot be converted to boolean;!xfails withbad operand type int for unary operator '!';0 < x < 10fails withbad operand types for binary operator '<'.
The third one looks familiar from math, but in Java 0 < x gives a boolean first, and a true cannot be compared with the number 10. A double comparison is written with &&: 0 < x && x < 10.
Common mistake
The zero check was put on the right:
int x = 0;
System.out.println(10 / x > 1 && x != 0); // ✗Exception in thread "main" java.lang.ArithmeticException: / by zeroJava evaluates && from left to right, so the division 10 / x runs first. The check x != 0 is never reached: the program stops with an exception. The guard must stand on the left: x != 0 && 10 / x > 1.
Key points
- The operators
==,!=,<,<=,>,>=give aboolean;==compares and=assigns. &&is true when both sides are true,||when at least one is, and!flips the answer.&&and||evaluate from left to right and skip the right side once the answer is known.- Wherever a yes-or-no answer is needed, Java accepts only a
boolean, never a number.