Learn Java · lesson 10 of 61 · about 7 minutes
Comparisons and boolean
Let the ticket desk spot a big group: compare values, store the answer in a boolean, and compare Strings with equals.
What you'll learn
- Use the six comparison operators
- Store results in boolean variables
- Compare Strings with equals
Yes-or-no questions
Your ticket desk knows how many tickets a group wants, but not whether that's a big group. A comparison answers a question like is it 10 tickets or more? The answer is a boolean: true or false, and Java prints it as that word.
Asking questions
== != < > <= >= compare numbers and give a boolean: true or false.
For Strings, use .equals(), not ==. == checks whether two variables refer to the very same object, which is usually not what you mean. You'll see why later in the course.
A big group
public class Main {
public static void main(String[] args) {
int tickets = 12;
boolean bigGroup = tickets >= 10;
System.out.println("Big group: " + bigGroup);
System.out.println(tickets == 10);
System.out.println(tickets != 0);
}
}Output
Big group: true
false
trueComparisons
public class Main {
public static void main(String[] args) {
int score = 72;
boolean passed = score >= 50;
System.out.println(passed + " " + (score == 100));
String answer = "def";
System.out.println(answer.equals("def") + " " + answer.equals("DEF"));
System.out.println(answer.equalsIgnoreCase("DEF"));
}
}Output
true false
true false
trueTip
= stores a value and == compares two. Read them aloud as gets and equals, and the slip is easier to spot.
Now try it yourself
This lesson is free in Codiqo, with 10 questions on what you just read. You can only learn to code by writing code, so it ends with a short program you write yourself, which we run and check straight away.