Sub topic 2
Run One Block with if and else
A printer has six sheets of paper. If someone asks to print four pages, the printer can take the job. If someone asks for seven pages, it should turn the job down. The same program can make both choices. It checks how much paper it has before it acts.
In Java, an if statement runs code only when a condition is true. A condition is an expression that gives a boolean value: true or false. Add else when you want different code to run if the condition is false.
You’ll start with an optional low-paper notice. Then you’ll use if and else to decide whether to accept a print job. In both examples, you’ll see where to put code that should run no matter what the program decides.
Use if for an optional action
Say the printer should warn you when it has five sheets or fewer. It should report that it is ready whether or not it shows the warning. So the warning goes inside the if, and the ready message goes after it.
Save this program as PaperNotice.java.
public class PaperNotice {
public static void main(String[] args) {
int sheetsLeft = 3;
if (sheetsLeft <= 5) {
System.out.println("Paper is running low.");
}
System.out.println("Printer is ready.");
}
}Compile the program and run it from the folder where you saved the file.
javac PaperNotice.java
java PaperNoticeYou should see this output, which is the text the program prints:
Paper is running low.
Printer is ready.Read the if from top to bottom
- Java stores 3 in sheetsLeft.
- Java reaches if and checks the condition inside the parentheses. The comparison asks, “Is 3 less than or equal to 5?” The answer is true.
- Java runs the print statement inside the curly braces. A statement is an instruction in the program. A group of statements inside curly braces is called a block. This block has just one statement.
- Java reaches the closing brace of the if block. It continues with the next statement and prints the ready message.
Now change sheetsLeft to 8. Save, compile, and run the program again. The condition is false because 8 is greater than 5. Java skips the whole if block and goes straight to the ready message.
Printer is ready.The ready message is not part of the decision. It is outside the block, so it runs in both tests. The blank line before it makes that easier to see, but the blank line does not change what Java does. The closing brace marks the end of the block.
Add else for the other outcome
An if on its own works for the low-paper notice: there is nothing extra to say when the printer has plenty of paper. But when a person sends a print job, silence is not helpful. The person should find out whether the job was accepted or turned down.
An else block tells Java what to do when the if condition is false. It does not need a condition of its own. In an if and else pair, Java picks one of two branches. A branch is a path the program can take. When the condition is true, Java takes the if branch and skips the else branch. When it is false, Java skips the if branch and takes the else branch.
Work through a print job
Save this program as PrintJob.java. To keep the example simple, each page needs one sheet. The program uses small, positive numbers for the print request and does not send anything to a real printer.
public class PrintJob {
public static void main(String[] args) {
int sheetsLeft = 6;
int pagesRequested = 4;
if (pagesRequested <= sheetsLeft) {
System.out.println("Job accepted.");
sheetsLeft = sheetsLeft - pagesRequested;
} else {
System.out.println("Not enough paper.");
}
System.out.println("Sheets left: " + sheetsLeft);
}
}javac PrintJob.java
java PrintJobJob accepted.
Sheets left: 2To trace a program, follow its statements in order and keep track of the values that change. Here is the trace for this run:
- The job asks for 4 pages, and the printer has 6 sheets.
- Java checks whether 4 is less than or equal to 6. It is, so Java enters the if block.
- The first statement in the block prints “Job accepted.”
- The next statement subtracts 4 from 6 and stores the result, 2, back in sheetsLeft. Java works out the right side of the equals sign before storing the new value on the left.
- Java skips the else block. It then prints the number of sheets left. The plus sign in the last statement joins the text and the number for display.
Notice that both statements in the if block run. Java does not pick just one statement from that block. It picks the branch, then runs the statements inside it in order. It also does not go back to check the condition after the subtraction. The decision for this job has already been made.
Trace the false path
Change pagesRequested to 7. Leave sheetsLeft at 6 in the source file. Save, compile, and run again.
Not enough paper.
Sheets left: 6The program starts with 6 sheets again. It does not keep the value of 2 from the last run. This time, 7 is not less than or equal to 6, so the condition is false. Java skips both statements in the if block. It does not print “Job accepted,” and it does not use any paper. The else block prints the reason the job was turned down.
The last statement still runs because it is after both blocks. It reads the current value of sheetsLeft. On the true path that value has changed. On the false path it has not. One statement can report the right number in either case.
Test the exact limit
A boundary is the point where a small change can flip the choice. Here, 6 pages fit and 7 do not. Try a request for exactly 6 pages. The program should accept the job and report 0 sheets left. An empty tray after the job is fine. What matters is that there are enough sheets before the job starts.
| Pages requested | Sheets at the start | Message | Sheets at the end |
|---|---|---|---|
| 4 | 6 | Job accepted. | 2 |
| 6 | 6 | Job accepted. | 0 |
| 7 | 6 | Not enough paper. | 6 |
The equals part of the less-than-or-equal-to operator is easy to miss. If you use only the less-than operator, a request for 4 still works and a request for 7 still fails. Those two tests would not show the mistake. The request for exactly 6 would: the program would turn down a job that fits.
Put each statement where it belongs
Before you write the braces, ask when each action should happen. For the print job, accepting the job and using the paper belong together. Turning down the job belongs in the other block. Reporting how much paper is left belongs after the choice.
| When an action should happen | Where to put it |
|---|---|
| Only when the condition is true | Inside the if block |
| Only when the condition is false | Inside the else block |
| After either branch finishes | After the closing brace of the else block |
Try moving the final print statement in PrintJob into the else block, just below the line that prints “Not enough paper.” Run it with 7 pages, then with 4. The 7-page run still reports the number of sheets. The 4-page run no longer does. The count did not stop working. You moved the statement that shows it onto a path the 4-page job does not take. Move the line back to restore the original behavior.
The same test helps with changes to values. Suppose you moved the subtraction after both blocks. The program would now use paper even for a job it turned down. With 7 pages and 6 sheets, it would report minus 1 sheet. That result is a clue: a statement that should run only on the true path is now running on both paths.
Keep a result you need after the blocks
Sometimes the two branches choose a message, and you want to print it afterward. Declare the variable before the if. To declare a variable is to give it a type and a name. Assigning a value means storing a value in it.
Save this version as PrintMessage.java.
public class PrintMessage {
public static void main(String[] args) {
int sheetsLeft = 6;
int pagesRequested = 7;
String message;
if (pagesRequested <= sheetsLeft) {
message = "Job accepted.";
} else {
message = "Not enough paper.";
}
System.out.println(message);
}
}javac PrintMessage.java
java PrintMessageThis version prints “Not enough paper.” Change the request to 4, then save, compile, and run again. The same print statement now prints “Job accepted.”
Scope is the part of the code where you can use a name. Here, message is declared before both blocks, so both branches can use it, and so can the print statement below them. If you declared message inside the if block, you could not use that name after the closing brace of that block. Declaring another variable with the same name inside else would not fix it. You would have two separate variables, neither one available to the final print statement.
Notice that the line declaring message does not give it a value. That is safe here because both branches assign a value before the program tries to print it. If you remove one of those assignments, Java will not compile the program. There would be a path to the print statement on which message had never been given a value.
Check common mistakes
Trust braces, not spacing
Indentation is the space at the start of a line. Use it to show which statements are inside a block. Java uses the braces, not the indentation, to tell where the block ends. If a line looks like it belongs to the if but is below the closing brace, it is not part of that if block.
Keep braces even when there is only one statement inside. Java lets you leave them out for a single statement. The risk comes later: if you add a second statement and indent it to match, that new statement is still not controlled by the if. With braces already in place, you can add a line inside the block and see where it belongs.
Do not put a semicolon after the condition
The semicolon ends many Java statements, such as a print statement. Do not put one between the closing parenthesis of an if condition and its opening brace. There, a semicolon counts as an empty statement. In an if without an else, this can make Java treat the following braced block as separate from the if. The block then runs even when the condition is false. With an else after that separate block, the program will not compile.
Keep the condition a true-or-false question
The number of sheets alone is not a condition in Java. Ask a question about the number instead. The low-paper notice asks whether the count is at most 5. The print job asks whether the request is at most the count. Read the comparison out loud and check which value goes on each side. If you reverse the values but leave the operator alone, you ask a different question.
Practice the two paths
Predict what will happen before you run the code. For each test, name the branch, note any value that changes, and then read the statements after the blocks.
Exercise
In PaperNotice, set sheetsLeft to 5. Which messages print, and in what order? What changes if you set it to 6?
Show answer
At 5, the condition is true, so “Paper is running low.” prints first. Then “Printer is ready.” prints. At 6, the condition is false, so only “Printer is ready.” prints.
Exercise
In PrintJob, start with 6 sheets and ask for 6 pages. Which branch runs? What does the last line print? Check your prediction by running the program.
Show answer
The if branch runs because 6 is less than or equal to 6. It prints “Job accepted.” and subtracts 6 from sheetsLeft. The else block is skipped. The last line prints “Sheets left: 0”.
Exercise
In PrintMessage, suppose the if branch still assigns message but the else block is empty. Why does Java reject the final print statement, even if you plan to request only 4 pages?
Show answer
The final print statement can be reached from either branch. On the false path, nothing gives message a value. Assign a message in both branches so the final statement can use it no matter which branch runs.