Sub topic 1
Build Conditions That Evaluate to true or false
A condition is a test that gives one of two answers: true or false. For example, “Is the score at least 70?” is a condition. A score of 85 makes it true. A score of 69 makes it false.
In Java, boolean is the type for values that are either true or false. You can store the result of a test in a boolean variable, print it, or combine it with another test. Later, you can use that result to decide which code runs. In this chapter, you will print the results so you can see how Java works them out.
Compare Two Values
An expression is a piece of code that produces a value. The expression 60 + 10 produces the number 70. The expression 85 >= 70 produces the boolean value true.
A comparison operator is a symbol that checks how two values relate. The operator >= means “greater than or equal to.” In other words, it means “at least.” That makes score >= 70 a direct way to ask whether a score is at least 70.
Save this program as Main.java and run it. Use the same file name when you try the other programs in this chapter.
public class Main {
public static void main(String[] args) {
int score = 85;
boolean passed = score >= 70;
System.out.println(passed);
System.out.println(score >= 90);
}
}The first line of output is true. Java compares 85 with 70 and stores the result in passed. The second line is false. There is no need for a new variable there: Java works out the comparison and prints the result right away.
Change score to 70 and predict both lines before running the program again. The first line still prints true because >= includes equality. Now try 69. Both lines print false.
Pick the operator that matches the rule
| Operator | Read it as | Example | Result |
|---|---|---|---|
| < | Less than | 70 < 70 | false |
| <= | Less than or equal to | 70 <= 70 | true |
| > | Greater than | 85 > 70 | true |
| >= | Greater than or equal to | 70 >= 70 | true |
| == | Equal to | 85 == 70 | false |
| != | Not equal to | 85 != 70 | true |
A boundary is a value where the answer can change. For the rule “at least 70,” the boundary is 70. Testing only 85 will not show you whether you used > or >= by mistake, because both tests are true for 85. Try 69, 70, and 71. The value at the boundary is the one that tells you whether your test includes it.
Watch for rules that sound close but mean different things. “Under 18” means age < 18. “18 or younger” means age <= 18. Ask whether someone who is exactly 18 should count before you pick the operator.
Tell assignment and comparison apart
Assignment means storing a value in a variable. A single equals sign does that: score = 70 stores 70 in score. A double equals sign tests equality: score == 70 asks whether score already holds 70. It does not change score.
This mix-up is easy to miss with boolean variables. Writing ready = true sets ready to true. The assignment itself also produces true, so Java can accept it where you meant to make a test. If you simply want to know whether ready is true, use ready on its own. It already holds the answer.
For numbers such as score, == tests whether the values are equal. A String is Java’s type for text. To test whether two strings contain the same text, use a call such as "yes".equals(answer). With strings, == asks whether both sides refer to the same object, not whether they contain the same letters. It can seem to work in a small test and still be the wrong check.
Combine Conditions with and, or, and not
A logical operator works with boolean values. Use one when a rule depends on more than one test, or when you need the opposite of a test.
- && means “and.” Both sides must be true.
- || means “or.” At least one side must be true. Both sides can be true.
- ! means “not.” It changes true to false and false to true.
A truth table lists the possible inputs and their results. Here, A and B stand for any two boolean values.
| A | B | A && B | A \ | \ | B |
|---|---|---|---|---|---|
| false | false | false | false | ||
| false | true | false | true | ||
| true | false | false | true | ||
| true | true | true | true |
The last row is worth a second look. In everyday speech, “or” can mean “one or the other, but not both.” In Java, || includes the case where both are true.
The not operator needs just one value. If isFull is false, !isFull is true. Read it as “the room is not full.” To reverse a whole comparison, put the comparison in parentheses: !(score >= 70) means “the score is not at least 70.” For this rule, score < 70 is shorter and says the same thing.
Work through a sign-up rule
A workshop accepts learners aged 12 through 17. Each learner needs either a signed permission form or a school booking. The room must also have space. Start by writing one test for each part of the rule.
public class Main {
public static void main(String[] args) {
int age = 12;
boolean hasPermission = false;
boolean hasSchoolBooking = true;
boolean isFull = false;
boolean eligibleAge = age >= 12 && age <= 17;
boolean hasApproval = hasPermission || hasSchoolBooking;
boolean canJoin = eligibleAge && hasApproval && !isFull;
System.out.println("Eligible age: " + eligibleAge);
System.out.println("Has approval: " + hasApproval);
System.out.println("Can join: " + canJoin);
}
}Here is how to trace the code. To trace code is to follow it one step at a time and work out what it does.
- The learner is 12. Both age checks are true, so eligibleAge is true.
- There is no permission form, but there is a school booking. One true value is enough for ||, so hasApproval is true.
- The room is not full, so !isFull is true. All three parts of the final “and” test are true, so canJoin is true.
The program prints true on all three lines. Now set age to 18. The first and third results change to false, but the second stays true. A booking still counts as approval. It just cannot make up for an age outside the range.
Group the parts of a rule
Parentheses show which parts of an expression belong together. Java also has a built-in order for grouping operators when you leave out parentheses. That order is called precedence. Like multiplication before addition in math, && groups more tightly than ||.
For a moment, set aside the room check. Suppose you write eligibleAge && hasPermission || hasSchoolBooking. Java groups it as (eligibleAge && hasPermission) || hasSchoolBooking. A school booking alone would make this true, even for someone aged 18.
Instead, write eligibleAge && (hasPermission || hasSchoolBooking). The parentheses make the two ways to get approval one unit. That way, eligibleAge must be true no matter which kind of approval the learner has. A separate variable like hasApproval makes the same grouping clear. It also gives you a result you can print when something looks wrong.
Know When Java Skips a Test
To evaluate an expression means to work out its value. Java starts with the left side of && or ||. Sometimes that side already tells Java the final answer. When Java skips the right side for that reason, it is using short-circuit evaluation.
| Operator | When Java skips the right side | Why it can skip | Column | Column |
|---|---|---|---|---|
| && | The left side is false | Both sides must be true, so the result is already false. | ||
| \ | \ | The left side is true | One true side is enough, so the result is already true. |
In the other two cases, Java needs the right side. If the left side of && is true, the right side decides the result. If the left side of || is false, the right side decides the result.
Put a safety check first
Say you have 8 portions of food and want to know whether every person in a group can get at least 2 whole portions. Java cannot divide a whole number by zero. Check the group size first so the division only runs when it is safe.
public class Main {
public static void main(String[] args) {
int portions = 8;
int people = 0;
boolean canServeGroup = people > 0 && portions / people >= 2;
boolean noShortage = people == 0 || portions / people >= 2;
System.out.println("Can serve a group: " + canServeGroup);
System.out.println("No shortage: " + noShortage);
}
}With zero people, the program prints false for canServeGroup. The left side of the && is false, so Java skips the division. It prints true for noShortage. Having no one to feed counts as no shortage, and the left side of the || is true. Again, Java skips the division. The answers differ because the two tests ask different questions.
Now change people to 4. In both expressions, Java needs the right side. Eight portions divided among four people gives two each, so both results are true. Try 5 next. Since the numbers are of type int, which holds whole numbers, Java drops the fraction from 8 / 5. Each person can get only one whole portion, and both tests are false.
The check people > 0 is a guard: a test placed before another step to make sure that step is safe. The order matters. In this example, putting the division first would cause an error when people is zero. A later check cannot protect a step that Java has already tried to run.
Check Your Conditions Before You Use Them
Start with the rule in words. If it says “at least,” check whether your operator includes the boundary. If it says “both,” look for &&. If it says “either,” decide whether having both should count before using ||. If a condition feels hard to read, name one part with a boolean variable and print that part on its own.
Test values that can prove your rule wrong. For the workshop, try 11, 12, 17, and 18 while holding the other inputs fixed. Then pick an allowed age and try each path to approval: permission only, booking only, both, and neither. Finally, set isFull to true with all other checks passing. You want to see both true and false for the final result, and you want to know why each one happened.
Exercise
A discount is for people aged 65 or older. Which comparison should you write? What results should you expect at ages 64, 65, and 66?
Show answer
Write age >= 65. The results are false at 64, true at 65, and true at 66. The rule includes 65 itself.
Exercise
In the workshop program, age is 17, hasPermission is true, hasSchoolBooking is true, and isFull is true. What are the values of eligibleAge, hasApproval, and canJoin?
Show answer
eligibleAge is true because 17 is in range. hasApproval is true because || allows both sides to be true. canJoin is false because !isFull is false, and the final test needs all three parts to be true.
Exercise
When people is zero, which condition skips the division: people > 0 && portions / people >= 2, or portions / people >= 2 && people > 0? Explain why.
Show answer
The first one skips the division. Java checks people > 0 first, gets false, and knows the whole && test is false. The second one tries to divide before checking people and causes an error.