- The Java Workshop
- David Cuartielles Andreas G?ransson Eric Foster Johnson
- 2944字
- 2021-06-11 13:05:19
Controlling the Flow of Your Programs
Imagine paying a bill from your e-wallet. You will only be able to make the payment if the credit balance in your e-wallet is greater than or equal to the bill amount. The following flowchart shows a simple logic that can be implemented:

Figure 2.1: A representative flow chart for an if-else statement
Here, the credit amount dictates the course of action of the program. To facilitate such scenarios, Java uses the if statement.
With the if statement, your application will execute a block of code if (and only if) a particular condition is true. In the following code, if the happy variable is true, then the block of code immediately following the if statement will execute. If the happy variable is not true, then the block of code immediately following the if statement will not execute.
boolean happy = true;// initialize a Boolean variable as true
if (happy) //Checks if happy is true
System.out.println("I am happy.");
Exercise 1: Creating a Basic if Statement
In most software industries, you are only working on a module of the code, and you might already know the value stored in a variable. You can use if statements and print statements in such cases. In this exercise, use an if statement to check if the values of variables assigned are true or false:
- Create a directory for examples from this chapter and others. Name the folder sources.
- In IntelliJ, select File -> New -> Project from the File menu.
- In the New Project dialog box, select a Java project. Click Next.
- Check the box to create the project from a template. Click on Command Line App. Click on Next.
- Name the project chapter02.
- For the project location, click the button with three dots (…) and then select the sources folder you created previously.
- Delete the base package name so that this entry is left blank. You will use Java packages in the Chapter 6, Libraries, Packages, and Modules.
- Click Finish.
IntelliJ will create a project named chapter02, as well as a src folder inside chapter02. This is where your Java code will reside. IntelliJ also creates a class named Main:
public class Main {
public static void main(String[] args) {
// write your code here
}
}
Rename the class named Main to Exercise01. (We're going to create a lot of small examples in this chapter.)
- Double-click in the text editor window on the word Main and then right-click it.
- From the contextual menu, select Refactor | Rename…, enter Exercise01, and then press Enter.
You will now see the following code:
public class Exercise01 {
public static void main(String[] args) {
// write your code here
}
}
- Within the main() method, define two Boolean variables, happy and sad:
boolean happy = true;
boolean sad = false;
- Now, create two if statements, as follows:
if (happy)
System.out.println("I am happy.");
// Usually put the conditional code into a block.
if (sad) {
// You will not see this.
System.out.println("The variable sad is true.");
}
The final code should look similar to this:
public class Exercise01 {
public static void main(String[] args) {
boolean happy = true;
boolean sad = false;
if (happy)
System.out.println("I am happy.");
// Usually put the conditional code into a block.
if (sad) {
// You will not see this.
System.out.println("The variable sad is true.");
}
}
}
- Click the green arrow that is just to the left of the text editor window that points at the class name Exercise01. Select the first menu choice, Run Exercise01.main().
- In the Run window, you'll see the path to your Java program, and then the following output:
I am happy.
The line I am happy. comes from the first if statement, since the happy Boolean variable is true.
Note that the second if statement does not execute, because the sad Boolean variable is false.
You almost always want to use curly braces to define the code block following an if condition. If you don't, you may find odd errors in your programs. For example, in the following code, the second statement, which sets the i variable to zero, will always get executed:
if (i == 5)
System.out.println("i is 5");
i = 0;
Unlike languages such as Python, indentation doesn't count in Java. The following shows what will actually execute with greater clarity:
if (i == 5) {
System.out.println("i is 5");
}
i = 0;
The last line is always executed because it is outside the if statement after the curly braces closes.
Comparison Operators
In addition to Java's Booleans, you can use comparisons in conditional statements. These comparisons must form a Boolean expression that resolves to true or false. Comparison operators allow you to build Boolean expressions by comparing values. Java's main comparison operators include the following:

Figure 2.2: The comparison operators in Java
The comparison operators such as == do not work the way you would expect for textual values. See the Comparing Strings section later in this chapter to see how to compare text values.
Note
A single equals sign, =, is used to assign a value. Two equals signs, ==, is used to compare values. Therefore, generally, you never use = in a Boolean expression to check a condition.
Exercise 2: Using Java Comparison Operators
An online retail store provides free delivery only if the destination is within a 10-kilometer (km) radius of the store. Given the distance between the nearest store location and home, we can code this business logic with comparison operators:
- In the Project pane in IntelliJ, right-click on the folder named src.
- Choose New -> Java Class from the menu.
- Enter Exercise02 for the name of the new class.
- Define the method named main():
public static void main(String[] args) {
}
- Inside the main() method, define the variables we'll use for comparisons:
int maxDistance = 10; // km
int distanceToHome = 11;
- Enter the following if statements after the variable declarations:
if (distanceToHome > maxDistance) {
System.out.println("Distance from the store to your home is");
System.out.println(" more than " + maxDistance + "km away.");
System.out.println("That is too far for free delivery.");
}
if (distanceToHome <= maxDistance) {
System.out.println("Distance from the store to your home is");
System.out.println(" within " + maxDistance + "km away.");
System.out.println("You get free delivery!");
}
The final code should look similar to the following: https://packt.live/32Ca9YS
- Run the Exercise02 program using the green arrow to the left.
In the Run window, you'll see the path to your Java program, and then the following output:
Distance from the store to your home is
more than 10km away.
That is too far for free delivery.
Nested if Statements
Nesting implies embedding a construct within another code construct. You can nest if statements within any block of code, including the block of code that follows an if statement. Here is an example of how the logic in a nested if statement is evaluated:

Figure 2.3: A representative flow chart for a nested if-else statement
Exercise 3: Implementing a Nested if Statement
In the following exercise, we will nest an if statement within another if statement to check if the speed of the vehicle is above the speed limit, and if so, whether it is above the finable speed:
- Using the techniques from the previous exercise, create a new class named Exercise03.
- Declare the speed, speedForFine, and maxSpeed variables with the values of 75, 70, and 60 respectively:
public class Exercise03 {
public static void main(String[] args) {
int speed = 75;
int maxSpeed = 60;
int speedForFine = 70;
}
}
- Create a nested if statement, where the outer if statement checks if the speed is greater than or equal to the maximum speed limit, and the inner loop checks if the speed is greater than or equal to the speed limit for a fine:
// Nested if statements.
if (speed <= maxSpeed) {
System.out.println("Speed is less than or equal to the max. speed limit");
if (speed < maxSpeed) {
System.out.println("Speed is less than the max. speed limit");
}
- Run the Exercise03 program using the green arrow to the left.
In the Run window, you'll see the path to your Java program, and then the following output:
You're over the speed limit
You are eligible for a fine!
Note
Try changing the value of speed in the code and then running the program again. You will see how different speed values produce different outputs.
Branching Two Ways with if and else
An else statement following the code block for an if statement gets executed if the if statement condition is not true. You can also use else if statements to provide for an additional test.
The basic syntax is as follows:
if (speed > maxSpeed) {
System.out.println("Your speed is greater than the max. speed limit");
} else if (speed < maxSpeed) {
System.out.println("Your speed is less than the max. speed limit");
} else {
System.out.println("Your speed is equal to the max. speed limit");
}
The third line (in the else block) will only print if neither of the first two lines (the if or else if code blocks) was true. Whatever the value of speed, only one of the lines will print.
Exercise 4: Using if and else Statements
A fair-trade coffee roaster offers a discount of 10% if you order more than 5 kg of whole coffee beans, and a discount of 15% if you order more than 50 kg. We'll code these business rules using if, else if, and else statements:
- Using the techniques from the previous exercise, create a new class named Exercise04.
- Enter the main method and declare the variables as follows:
public static void main(String[] args) {
int noDiscount = 0;
int mediumDiscount = 10; // Percent
int largeDiscount = 15;
int mediumThreshold = 5; // Kg
int largeThreshold = 50;
int purchaseAmount = 40;
}
- Enter the following if, else if, and else statements:
if (purchaseAmount >= largeThreshold) {
System.out.println("You get a discount of " + largeDiscount + "%");
} else if (purchaseAmount >= mediumThreshold) {
System.out.println("You get a discount of " + mediumDiscount + "%");
} else {
// Sorry
System.out.println("You get a discount of " + noDiscount + "%");
}
Notice that we check against the largest threshold first. The reason for this is that a value greater than or equal to largeThreshold will also be greater than or equal to mediumThreshold.
Note
The full source code for this exercise can be found at: https://packt.live/33UTu35.
- Run the Exercise04 program using the green arrow to the left.
In the Run window, you'll see the path to your Java program, and then the following output:
You get a discount of 10%
Using Complex Conditionals
Java allows you to create complex conditional statements with logical operators. Logical operators are generally used on only Boolean values. Here are some of the logical operators available in Java:
- AND (&&): a && b will be evaluated to true if both a and b are true
- OR (||): a || b will be evaluated to true if either a or b, or both are true
- NOT (!): !a be evaluated to true if a is false
Use the conditional operators to check more than one condition in an if statement. For example, the following shows an if statement where both conditions must be true for the overall if statement to execute:
boolean red = true;
boolean blue = false;
if ((red) && (blue)) {
System.out.println("Both red AND blue are true.");
}
In this case, the overall expression resolves to false, since the blue variable is false, and the print statement will not execute.
Note
Always use parentheses to make your conditionals clear by grouping the conditions together.
You can also check if either, or both, of the expressions are true with the || operator:
boolean red = true;
boolean blue = false;
if ((red) || (blue)) {
System.out.println("Either red OR blue OR both are true.");
}
In this case, the overall expression resolves to true, since at least one part is true. Therefore, the print statement will execute:
boolean blue = false;
if (!blue) {
System.out.println("The variable blue is false");
}
The value of blue is initialized to false. Since we are checking the NOT of the blue variable in the if statement, the print statement will execute. The following exercise shows how we can use logical operators.
Exercise 5: Using Logical Operators to Create Complex Conditionals
This exercise shows an example of each of the conditional operators previously described. You are writing an application that works with data from a fitness tracker. To accomplish this, you need to code a check against normal heart rates during exercise.
If a person is 30 years old, a normal heart rate should be between 95 beats per minute (bpm) and 162 bpm. If the person is 60 years old, a normal heart rate should be between 80 and 136 bpm.
Use the following steps for completion:
- Using the techniques from the previous exercise, create a new class named Exercise05 in the main method and declare variables.
public static void main(String[] args) {
int age = 30;
int bpm = 150;
}
- Create an if statement to check the heart rate of a 30-year old person:
if (age == 30) {
if ((bpm >= 95) && (bpm <= 162)) {
System.out.println("Heart rate is normal.");
} else if (bpm < 95) {
System.out.println("Heart rate is very low.");
} else {
System.out.println("Heart rate is very high.");
}
We have nested conditionals to check the allowable range for 30-year-olds.
- Create an else if statement to check the heart rate of a 60-year old person:
} else if (age == 60) {
if ((bpm >= 80) && (bpm <= 136)) {
System.out.println("Heart rate is normal.");
} else if (bpm < 80) {
System.out.println("Heart rate is very low.");
} else {
System.out.println("Heart rate is very high.");
}
}
We have nested conditionals to check the allowable range for 60-year-olds.
- Run the Exercise05 program using the green arrow to the left.
In the Run window, you'll see the path to your Java program, and then the following output:
Heart rate is normal.
- Change age to 60 and re-run the program; your output should be as follows:
Heart rate is very high.
Note
The full source code for this exercise can be found at: https://packt.live/2W3YAHs.
Using Arithmetic Operators in an if Condition
You can use arithmetic operators as well in Boolean expressions, as shown in Example01.java:
public class Example01 {
public static void main(String[] args) {
int x = 2;
int y = 1;
if ((x + y) < 5) {
System.out.println("X added to Y is less than 5.");
}
}
}
The output in this case would be as follows:
X added to Y is less than 5
Here, the value of (x + y) is calculated, and then the result is compared to 5. So, since the result of x added to y is 3, which is less than 5, the condition holds true. Therefore, the print statement is executed. Now that we have seen the variations of the if else statement, we will now see how we can use the ternary operator to express the if else statements.
The Ternary Operator
Java allows a short-hand version of an if else statement, using the ternary (or three-part) operator, ?:. This is often used when checking variables against an allowed maximum (or minimum) value.
The basic format is: Boolean expression ? true block : false block, as follows:
x = (x > max) ? max : x;
The JVM resolves the (x > max) Boolean expression. If true, then the expression returns the value immediately after the question mark. In this case, that value will be set into the x variable since the line of code starts with an assignment, x =. If the expression resolves to false, then the value after the colon, :, is returned.
Exercise 6: Using the Ternary Operator
Consider the minimum height requirement for a roller coaster to be 121 centimeters (cm). In this exercise, we will check for this condition using the ternary operator. Perform the following steps:
- Using the techniques from the previous exercise, create a new class named Exercise06.
- Declare and assign values to the height and minHeight variables. Also, declare a string variable to print the output message:
public static void main(String[] args) {
int height = 200;
int minHeight = 121;
String result;
- Use the ternary operator to check the minimum height requirement and set the value of result:
result = (height > minHeight) ? "You are allowed on the ride" : "Sorry you do not meet the height requirements";
System.out.println(result);
}
So, if height is greater than minHeight, the first statement will be returned (You are allowed on the ride). Otherwise, the second statement will be returned (Sorry you do not meet the height requirements).
Your code should look similar to this:
public class Exercise06 {
public static void main(String[] args) {
int height = 200;
int minHeight = 121;
String result;
result = (height > minHeight) ? "You are allowed on the ride" : "Sorry you do not meet the height requirements";
System.out.println(result);
}
}
- Run the Exercise06 program.
In the Run window, you'll see the path to your Java program, and then the following output:
You are allowed on the ride
Equality Can Be Tricky
Java decimal types such as float and double (and the object versions, Float and Double) are not stored in memory in a way that works with regular equality checks.
When comparing decimal values, you normally need to define a value that represents what you think is close enough. For example, if two values are within .001 of each other, then you may feel that is close enough to consider the values as equal.
Exercise 7: Comparing Decimal Values
In this exercise, you'll run a program that checks if two double values are close enough to be considered equal:
- Using the techniques from the previous exercise, create a new class named Exercise07.
- Enter the following code:
public class Exercise07 {
public static void main(String[] args) {
double a = .6 + .6 + .6 + .6 + .6 + .6;
double b = .6 * 6;
System.out.println("A is " + a);
System.out.println("B is " + b);
if (a != b) {
System.out.println("A is not equal to B.");
}
// Check if close enough.
if (Math.abs(a - b) < .001) {
System.out.println("A is close enough to B.");
}
}
}
The Math.abs() method returns the absolute value of the input, making sure the input is positive.
We will learn more about the Math package in Chapter 6, Libraries, Packages, and Modules.
- Run the Exercise07 program using the green arrow to the left.
In the run window, you'll see the path to your Java program, and then the following output:
A is 3.6
B is 3.5999999999999996
A is not equal to B.
A is close enough to B.
Note how a and b differ due to the internal storage for the double type.
Note
For more on how Java represents floating-point numbers, see https://packt.live/2VZdaQy.
Comparing Strings
You cannot use == to compare two strings in Java. Instead, you need to use the String class' equals method. This is because == with String objects just checks whether they are the exact same object. What you'll normally want is to check if the string values are equal:
String cat = new String("cat");
String dog = new String("dog");
if (cat.equals(dog)) {
System.out.println("Cats and dogs are the same.");
}
The equals method on a String object called cat returns true if the passed-in String, dog, has the same value as the first String. In this case, these two strings differ. So, the Boolean expression will resolve to false.
You can also use literal strings in Java, delineating these strings with double quotes. Here's an example:
if (dog.equals("dog")) {
System.out.println("Dogs are dogs.");
}
This case compares a String variable named dog with the literal string "dog".
Example09 shows how to call the equals method:
Example09.java
15 if (dog.equals(dog)) {
16 System.out.println("Dogs are dogs.");
17 }
18
19 // Using literal strings
20 if (dog.equals("dog")) {
21 System.out.println("Dogs are dogs.");
22 }
23
24 // Can compare using a literal string, too.
25 if ("dog".equals(dog)) {
26 System.out.println("Dogs are dogs.");
You should get the following output:
Cats and dogs are not the same.
Dogs are dogs.
Dogs are dogs.
Dogs are dogs.
Using switch Statements
The switch statement is similar to a group of nested if-else-if statements. With switch, you can choose from a group of values.
The basic syntax follows:
switch(season) {
case 1: message = "Spring";
break;
case 2: message = "Summer";
break;
case 3: message = "Fall";
break;
case 4: message = "Winter";
break;
default: message = "That's not a season";
break;
}
With the switch keyword, you place the variable to be checked. In this case, we're checking a variable called season. Each case statement represents one possible value for the switch variable (season). If the value of season is 3, then the case statement that matches will be executed, setting the message variable to the String Fall. The break statement ends the execution for that case.
The default statement is used as a catch-all for any unexpected value that doesn't match the defined cases. The best practice is to always include a default statement. Let's see how to implement this logic in a program.
Exercise 8: Using switch
In this exercise, you'll run a program that maps a number to a season:
- Using the techniques from the previous exercise, create a new class named Exercise08.
- Enter in the main() method and set up these variables:
public static void main(String[] args) {
int season = 3;
String message;
}
- Enter the following switch statement.
switch(season) {
case 1: message = "Spring";
break;
case 2: message = "Summer";
break;
case 3: message = "Fall";
break;
case 4: message = "Winter";
break;
default: message = "That's not a season";
break;
}
- And enter a println statement to show us the results:
System.out.println(message);
Note
You can find the code for this exercise here: https://packt.live/35WXm58.
- Run the Exercise08 program using the green arrow to the left.
In the Run window, you'll see the path to your Java program, and then the following output:
Fall
Because the season variable is set to 3, Java executes the case with 3 as the value, so in this case, setting the message variable to Fall.
Note
There is no one rule for when to use a switch statement as opposed to a series of if-else statements. In many cases, your choice will be based on the clarity of the code. In addition, switch statements are limited in only having cases that hold a single value, while if statements can test much more complicated conditions.
Normally, you'll put a break statement after the code for a particular case. You don't have to. The code will keep executing from the start of the case until the next break statement. This allows you to treat multiple conditions similarly.
Exercise 9: Allowing Cases to Fall Through
In this exercise, you will determine a temperature adjustment for the porridge in Goldilocks and the Three Bears. If the porridge is too hot, for example, you'll need to reduce the temperature. If it's too cold, raise the temperature:
- Using the techniques from the previous exercise, create a new class named Exercise09.
- Enter in the main() method and set up these variables:
public static void main(String[] args) {
int tempAdjustment = 0;
String taste = "way too hot";
}
- Next, enter the following switch statement:
switch(taste) {
case "too cold": tempAdjustment += 1;
break;
case "way too hot": tempAdjustment -= 1;
case "too hot": tempAdjustment -= 1;
break;
case "just right": // No adjustment
default:
break;
}
- Print out the results:
System.out.println("Adjust temperature: " + tempAdjustment);
- Run the Exercise09 program using the green arrow to the left.
In the run window, you'll see the path to your Java program, and then the following output:
Adjust temperature: -2
Look carefully at the switch statement. If the value of the taste variable is too cold, then increment the temperature by 1. If the value is too hot, decrement the temperature by 1. But notice there is no break statement, so the code keeps executing and adjusts the temperature down by another 1. This implies that if the porridge is too hot, the temperature is decremented by 1. If it's way too hot, it's decremented by 2. If the porridge is just right, there is no adjustment.
Note
Starting with Java 7, you can use Strings in switch statements. Prior to Java 7, you could not.
Using Java 12 Enhanced switch Statements
Java 12 offers a new form of the switch statement. Aimed at switch statements that are essentially used to determine the value of a variable, the new switch syntax allows you to assign a variable containing the result of the switch.
The new syntax looks like this:
int tempAdjustment = switch(taste) {
case "too cold" -> 1;
case "way too hot" -> -2;
case "too hot" -> -1;
case "just right" -> 0;
default -> 0;
};
This switch syntax does not use break statements. Instead, for a given case, only the code block after -> gets executed. The value from that code block is then returned as the value from the switch statement.
We can rewrite the Exercise09 example using the new syntax, as shown in the following exercise.
Note
IntelliJ needs a configuration to support Java 12 switch statements.
Exercise 10: Using Java 12 switch Statements
In this exercise, we will work on the same example as in the previous exercise. This time, though, we will implement the new switch case syntax that is made available by Java 12. Before we start with the program there, you'll have to make changes to the IntelliJ configuration. We will set that up in the initial few steps of the exercise:
- From the Run menu, select Edit Configurations.
- Click on Edit Templates.
- Click on Application.
- Add the following to the VM options:
--enable-preview
- Click OK.
This turns on the IntelliJ support for Java 12 enhanced switch statements.
- Using the techniques from the previous exercise, create a new class named Exercise10.
- Enter in the main() method and set up this variable:
public static void main(String[] args) {
String taste = "way too hot";
}
- Define a switch statement as follows:
int tempAdjustment = switch(taste) {
case "too cold" -> 1;
case "way too hot" -> -2;
case "too hot" -> -1;
case "just right" -> 0;
default -> 0;
};
Note the semi-colon after switch. Remember, we are assigning a variable to a value with the whole statement.
- Then print out the value chosen:
System.out.println("Adjust temperature: " + tempAdjustment);
- When you run this example, you should see the same output as in the previous example:
Adjust temperature: -2
The full code is as follows:
public class Exercise10 {
public static void main(String[] args) {
String taste = "way too hot";
int tempAdjustment = switch(taste) {
case "too cold" -> 1;
case "way too hot" -> -2;
case "too hot" -> -1;
case "just right" -> 0;
default -> 0;
};
System.out.println("Adjust temperature: " + tempAdjustment);
}
}
- Vue.js 3.x快速入門
- Visual Basic .NET程序設計(第3版)
- R語言經典實例(原書第2版)
- Python程序設計(第3版)
- PowerCLI Cookbook
- Java開發入行真功夫
- Expert Android Programming
- Elasticsearch for Hadoop
- Python編程:從入門到實踐
- Mastering Linux Network Administration
- 計算機應用基礎實踐教程
- Test-Driven Machine Learning
- ElasticSearch Cookbook(Second Edition)
- Learning Apache Karaf
- 智能手機APP UI設計與應用任務教程