In this article, we will look at loop constructs and decision logic . We will describe the different type of loop constructs and how to use them and then go into decision logic and how it is used within Java. This is part of a larger series of articles to help you prepare for the java associate exam. The previous article that you might want to read is, “Tutorial:Review of Java Arrays for the Java Certification Exam”.

Making Decision with Java

Making choices will be a fundamental element in all your programs. You need to be able to encode the business logic in Java. Whatever decision you make in programming terms requires the ability to make comparisons between variables, constants, and the values of expressions and then execute one group of statements or another, depending on the result of a given comparison. Thus, the first step to understanding how you make decisions in a program is to look at how you make comparisons.

Making Comparisons in Java

Java provides you with six relational operators for comparing two data values. The data values you are comparing can be variables, constants, or expressions with values drawn from Java's primitive data types (i.e. byte, short, int, long, char, float, or double). The table for Java Relational Operators is shown below:

Tutorial:Review of Java Loops and Logic for the Java Certification Exam-d5-javarelationaloperators.jpg
Table: Java Relational Operators

Each operator produces either the value true or the value false, and so is eminently suited to the business of making decisions. This also implies that you can use a boolean variable to store the result of a comparison. You saw how to declare variables of type boolean in the previous chapter. For example, you could define a boolean variable state and set its value to be the result of an expression using a comparison as follows:

Java Code: Comparison
boolean state = false;	// Define and initialize the variable 
state = x - y < a + b;	// Store the result of comparing x-y with a+b
The value of the variable state is set to true in the assignment statement if x - y is less than a + b, and to false otherwise. Note that if the left and right operands of a relational operator are of differing types, values are promoted in the same way as you saw in the previous chapter for mixed arithmetic expressions. So if aDouble is of type double and number is of type int in the following expression

Java Code:
aDouble < number + 1
the result of the expression number + 1 is calculated as type int, and this value is promoted to type double before comparing it with the value of aDouble.

The if Statement

The first statement you look at that can make use of the result of a comparison is the if statement. The if statement, in its simplest configuration, is of the form:

Java Code:
if(expression) 
   statement;
where expression can be any expression that produces a value true or false. You can see a graphical representation of this logic in the figure below:

Tutorial:Review of Java Loops and Logic for the Java Certification Exam-d5-ifstatement.jpg
Figure: If Statement Logic

If the value of expression is true, the statement that follows the if is executed; otherwise, it isn't. Below is a listing showing a practical example of an if statement:

Java Code: If Statement Example
if(number%2 != 0)	// Test if number is odd 
    ++number;	// If so make it even
The if condition between the parentheses tests whether the value of number is odd by comparing the remainder that results from dividing it by 2 with 0. If the remainder isn't equal to 0, the value of number is odd, so you add 1 to make it even. If the value of number is even, the statement incrementing number is not executed.

Statement Blocks

In general, wherever you can have one executable statement in Java, you can also have a block of statements enclosed between braces, {}. This applies to the statements within a statement block, so you can always nest a statement block between braces inside another statement block, and you can do this to any depth. The ability to use a block wherever you can have a statement means that you can use a statement block within the basic if statement that you just saw. Therefore, the if statement can equally well be of the following form:

Java Code: If Statement Blocks
if(expression) { 
   statement 1; 
   statement 2; 
   ...
   statement n;
}
Now if the value of expression is true, all the statements enclosed in the following block are executed; if expression is false, the statements in the block are not executed. Of course, without the braces to enclose the block, the code no longer has a statement block:

Java Code: If Statement Block
if(expression) statement 1; statement 2; ... statement n;
When an if statement has a statement block, then you can write the following:

Java Code: If Statement Block
if(number%2 != 0) {			// Test if number is odd 
   // If so make it even and output a message 
   ++number;
}
Statement blocks are more than just a convenient way of grouping statements together—they affect the life and accessibility of variables. Let's now look a little deeper into what you can do with the if statement.

The else Clause

You can extend the basic if statement by adding an else clause. This provides an alternative choice of statement, or statement block, that is executed when the expression in the if statement is false. You can see the syntax of this statement, and how the program's control flow works, in the figure below:

Tutorial:Review of Java Loops and Logic for the Java Certification Exam-d5-elsestatement.jpg
Figure: Else Clause Program Flow

This provides an explicit choice between two courses of action, one for when the if expression is true and another for when it is false. You can apply this in a console program and try out the random() method from the Math class at the same time.

Nested if Statements

The statement that is executed when an if expression is true can be another if, as can the statement in an else clause. This enables you to express very complex business logic. An if statement that is nested inside another can also itself contain a nested if. You can continue nesting ifs one inside the other like this for as long as you still know what you are doing or even beyond if you enjoy confusion. The listing below is a modified version of the previous example:

Java Code: Nested If Statements
if(number%2 == 0) {	// Test if it is even 
   if(number < 50) {	// Output a message if number is < 50
      System.out.println(“You have got an even number < 50, “ + number);
   }
} else { 
      System.out.println(“You have got an odd number, “ + number); // It is odd
}
With nested ifs, it is often difficult to discern which if statement to which a particular else clause belongs. If you remove the braces from the preceding code, you can have the following:

Java Code: Nested If Statement without Braces
if(number%2 == 0)	// Test if it is even 
   if(number < 50 )		// Output a message if number is < 50
      System.out.println(“You have got an even number < 50, “ + number); 
   else
      System.out.println(“You have got an odd number, “ + number); // It is odd
Note how the logic has substantially changed from the previous version, in spite of the fact that the indentation implies otherwise. You need to take care that the indenting of statements with nested ifs is correct. It is easy to convince yourself that the logic is as indicated by the indentation, even when this is completely wrong.

Comparing Enumeration Values

You can't compare variables of an enumeration type using the comparison operators but you can compare them using a method that every enumeration object provides. Suppose you define an enumeration type as:

Java Code: Enumeration Types
enum Season { spring, summer, fall, winter }
You can now define and initialize a variable of type Season with the following statement:

Java Code: Enumeration Value Statement
Season season = Season.summer;
If you later want to check what the season variable currently holds, you could write:

Java Code: Enumeration Values Example
if(season.equals(Season.spring)) { 
   System.out.println(“Spring is here, the grass is growing.”);
} else { 
   System.out.println(“It isn\’t Spring yet”);
}
This calls the equals() method for the enumeration referred to by season. This method compares the value in season with the value between the parentheses and results in true if they are equal or false if they are unequal. You could use the equals() method to compare season with another variable of type Season, for example:

Java Code: Enumeration Example Using a Variable
Season best = Season.winter;		// A new variable initialized to winter 
if(season.equals(best)) {
   System.out.println(“season is the same as best, and is equal to “+ best); 
} else {
   System.out.println(“ season has the value “+season + “ and best has the value “ + best);
}
After defining the variable, best, you test whether the value of season is the same value as best. If it is, the first output statement is executed. If best and season are not equal, the output statement in the else block is executed.

Logical Operators

Often you will need to combine a number of conditions in order to execute a particular course such as when all conditions are true simultaneously. You address these cases as well as using logical operators to combine several expressions that have a value true or false. Because they operate on boolean values, they are also referred to as boolean operators. There are six logical operators that operate on boolean values as shown in the table below:

Tutorial:Review of Java Loops and Logic for the Java Certification Exam-d5-logicaloperators.jpg
Figure: Logical Operators

The AND and OR operators are very simple; the only point of potential confusion is the fact that you have the choice of two operators for each of AND and OR. The extra operators are the bitwise & and | from the previous chapter that you can also apply to boolean values where they have an effect that is subtly different from && and ||. We will look in detail at the various operators.

Logical AND Operations

You can use either of the AND operators, && or &, where you have two logical expressions that must both be true for the result to be true. Either AND operator produces the same result from the logical expression. If we first explore how they are used. This applies equally well to & as well as to &&.

You can use the && operator if you test a variable of type char to determine whether it contains an uppercase letter or not. For example, you can have a value being tested that must be both greater than or equal to 'A' AND less than or equal to 'Z'. Both conditions must be true for the value to be a capital letter. You could implement a test for an uppercase letter in a single if by using the && operator in the following manner:

Java Code: &amp;&amp; Operator Example
if(symbol >= ‘A’ && symbol <= ‘Z’) 
   System.out.println(“You have the capital letter “ + symbol);
Here, the output statement is executed only if both of the conditions combined by the operator && are true. It is a good idea to add parentheses if they make the code easier to read and to help to avoid mistakes.

&& versus &

What distinguishes && from & is that the conditional && does not bother to evaluate the right-hand operand if the left-hand operand is false because the result is already determined in this case to be false. This can make the code a bit faster when the left-hand operand is false. An example of && is shown in the following statements:

Java Code: Statement Using Double Logical AND
int number = 50; 
if(number<40 && (3*number - 27)>100) {
   System.out.println(“number = “ + number); 
}
Here the expression (3*number - 27)>100 is never executed because the expression number<40 is always false. On the other hand, if you write the statements in the following manner:

Java Code: Statement Using Single Logical AND
int number = 50; 
if(number<40 & (3*number - 27)>100) {
   System.out.println(“number = “ + number);
}
the effect is different. The whole logical expression is always evaluated, so even though the left-hand operand of the & operator is false and the result is a foregone conclusion after that is known, the right- hand operand (3*number - 27)>100) is still evaluated.

In many cases, you use &&, but there are other occasions when you want to be sure that the right-hand operand is evaluated. Equally, in some instances, you want to be certain the right-hand operand won't be evaluated if the left operand is false.

Logical OR Operations

The OR operators, | and ||, apply when you want a true result if either or both of the operands are true. The logical OR, ||, works in a similar way to the && operator in that it omits the evaluation of the right- hand operand when the left-hand operand is true.
Obviously if the left operand for the || operator is true, the result is true regardless of whether the right operand is true or false. An example of a test using logical OR is shown below:

Java Code: Logical OR Operation
if(age < 16 || age >= 65) { 
   ticketPrice *= 0.9;	// Reduce ticket price by 10%
}
In this listing, both conditions cannot be true. With an | or an || operation, you get a false result only if both operands are false. If either or both operands are true, the result is true.

Exclusive OR Operations

The exclusive OR results is true when its operands are different, so when one operand has the value true and the other has the value false, the result is true. When both operands have the same value, either both true or both false, the result is false. Thus the exclusive OR operator is useful on those rare occasions when you want to establish whether or not two boolean values are different.

Boolean NOT Operations

The third type of logical operator, !, applies to one boolean operand, and the result is the inverse of the operand value. So if the value of a boolean variable state is true then the expression !state has the value false, and if it is false, then the state evaluates to true. An example of the use of this operator in an expression is shown below:

Java Code: Not Operators Example
if(!(age >= 16 && age < 65)) { 
   ticketPrice *= 0.9;				// Reduce ticket price by 10%
}
Applying the ! operator to the result of the expression does what you want. You could also apply the ! operator in an expression in the following manner:

Java Code:
!(Income > Expenditure)
Character Testing Using Standard Library Methods

Although testing characters using logical operators is a useful way of demonstrating how these operators work, in practice there is an easier way. The standard Java packages provide a range of standard methods to do the sort of testing for particular sets of characters such as letters or digits that you have been doing with if statements. They are all available within the Character class, which is automatically available in your programs. An example of a character test is shown below:

Java Code: Deciphering Characters Example
import static java.lang.Character.isLowerCase;
import static java.lang.Character.isUpperCase;
public class LetterCheck3 {
   public static void main(String[] args) { 
      char symbol = ‘A’; 
      symbol = (char)(128.0*Math.random());		// Generate a random character

      if(isUpperCase(symbol)) {
         System.out.println(“You have the capital letter “ + symbol);
      } else {
         if(isLowerCase(symbol)) {
            System.out.println(“You have the small letter “ + symbol); 
         } else {
            System.out.println(“The code is not a letter”);
         }
      }
   }
}
In the listing, the import statements for the isUpperCase and isLowerCase method allow you to call these methods without using the Character class name as qualifier. The isUpperCase() method returns true if the char value that you pass to it is uppercase, and false if it is not. Similarly, the isLowerCase() method returns true if the char value you pass to it is lowercase. The table below shows some of the other methods included in the Character class that you may find useful for testing characters:

Tutorial:Review of Java Loops and Logic for the Java Certification Exam-d5-usefultestingmethods.jpg
Figure: Useful Methods for Testing Characters

The Conditional Operator

The conditional operator is sometimes called a ternary operator because it involves three operands. It is best understood by looking at an example. For example you can have two variables of type int with the names yourAge and myAge, and you want to assign the greater of the values stored in yourAge and myAge to a third variable, older, which is also of type int. You can do this with the following statement:

Java Code:
older = yourAge > myAge ? yourAge : myAge;
The conditional operator is written generally as:

Java Code: Conditional Operator Syntax
logical_expression ? expression1 : expression2
If the logical_expression evaluates as true, the result of the operation is the value of expression1, and if logical_expression evaluates to false, the result is the value of expression2. Note that if expression1 is evaluated because logical_expression is true, then expression2 is not, and vice versa. You can use the conditional operator in lots of circumstances, and one common application of it is to control output, depending on the result of an expression or the value of a variable. You can vary a message by selecting one text string or another depending on the condition specified.

The Switch Statement

You use the switch statement to select from multiple choices that are identified by a set of fixed values for a given expression. The expression that selects a choice must produce a result of an integer type other than long, or a value of an enumeration type, or a string. Thus, the expression that controls a switch statement can result in a value of type char, byte, short, or int, an enumeration constant, or a String object.

The normal use the switch statement operates rather like a rotary switch in that you can select one of a fixed number of choices. For example, on some makes of washing machine you choose between the various machine settings in this way, with positions for cotton, wool, synthetic fiber, and so on, which you select by turning the knob to point to the option that you want. Here's a switch statement reflecting this logic for a washing machine:

Java Code: Switch Statement Example
switch(wash) { 
   case 1:	// wash is 1 for Cotton
      System.out.println(“Cotton selected”); 		// Set conditions for cotton... break;
   case 2:	// wash is 2 for Linen 
      System.out.println(“Linen selected”); // Set conditions for linen... break;
   case 3:	// wash is 3 for Wool 
      System.out.println(“Wool selected”); // Set conditions for wool... break;
   default:	// Not a valid value for wash 
      System.out.println(“Selection error”); break;
}
The selection in the switch statement is determined by the value of the expression that you place between the parentheses after the keyword switch. In this case it's simply the integer variable wash that would need to be previously declared as of type char, byte, short, or int. You define the possible switch options by one or more case values, also called case labels, which you define using the keyword case. In general, a case label consists of the case keyword followed by a constant value that is the value that selects the case, followed by a colon. The statements to be executed when the case is selected follow the case label.

The General Case of the switch Statement

The flowchart shown in the figure shows the logic of the general switch statement.

Tutorial:Review of Java Loops and Logic for the Java Certification Exam-d5-generalswitchstatement.jpg
Figure: General Case Switch Statement

Each case value is notionally compared with the value of an expression. If one matches then the code for that case is executed, and the break branches to the first statement after the switch. The logic for the switch statement is shown in the figure below:

Tutorial:Review of Java Loops and Logic for the Java Certification Exam-d5-switchwobreak.jpg
Figure: Switch Statement without a Break Statement

Now when a case label value is equal to the switch expression, the code for that case is executed and followed by the statements for all the other cases that succeed the case that was selected, including that for the default case if that follows. This is not usually what you want, so make sure you don't forget the break statements.

Variable Scope

The scope of a variable is the part of the program over which the variable name can be referenced — in other words, where you can use the variable in the program. Every variable that we have declared so far in the examples has been defined within the context of a method, the method main(). Variables that are declared within a method are called local variables, as they are only accessible within the confines of the method in which they are declared. However, they are not necessarily accessible everywhere in the code for the method in which they are declared. The listing below shows variables defined within nested blocks:

Java Code: Demonstration of Variable Scope
{
   int n = 1;				// Declare and define n
	
   // Reference to n is OK here 
   // Reference to m here is an error because m does not exist yet
   {
      // Reference to n here is OK too 
      // Reference to m here is still an error

      int m = 2;				// Declare and define m
      // Reference to m and n are OK here - they both exist
   }		// m dies at this point

   // Reference to m here is now an error 
   // Reference to n is still OK though
}			// n dies at this point so you can’t refer to it in following statements
A variable does not exist before its declaration; you can refer to it only after it has been declared. It continues to exist until the end of the block in which it is defined, and that includes any blocks nested within the block containing its declaration. The variable n is created as the first statement in the outer block. It continues to exist within the inner block too. The variable m exists only within the inner block because that's where its declaration appears. After the brace at the end of the inner block, m no longer exists so you can't refer to it. The variable n is still around, though, and it survives until the closing brace of the outer block.

The rule that determines the accessibility of local variables is simple. Local variables are accessible only from the point in the program where they are declared to the end of the block that contains the declaration. At the end of the block in which they are declared, they cease to exist. I can demonstrate this with an example.

Using Loops

A loop enables you to execute a statement or block of statements repeatedly. The need to repeat a block of code arises in almost every program. If you did the first exercise at the end of the last chapter, based on what you had learned up to that point, you would have come up with a program along the lines of the following:

Java Code: Example Not Using a Loop
public class TryExample1_1 { 
   public static void main(String[] args) {
      byte value = 1; 
      value *= 2; 
      System.out.println(“Value is now “+value); 
      value *= 2; 
      System.out.println(“Value is now “+value); 
      value *= 2; 
      System.out.println(“Value is now “+value); 
      value *= 2; 
      System.out.println(“Value is now “+value); 
      value *= 2; 
      System.out.println(“Value is now “+value); 
      value *= 2; 
      System.out.println(“Value is now “+value); 
      value *= 2; 
      System.out.println(“Value is now “+value); 
      value *= 2; 
      System.out.println(“Value is now “+value);
   }
}
The same pair of statements has been entered eight times. This is a rather tedious way of doing things. If the program for the company payroll had to include separate statements to do the calculation for each employee, it would never get written. A loop removes this sort of difficulty. You can write the method main() to do the same as the preceding code like so:

Java Code: Loop Example
public static void main(String[] args) { 
   byte value = 1; 
   for(int i = 0 ; i < 8 ; ++i) {
      value *= 2; 
      System.out.println(“Value is now “ + value);
   }
}
This uses one particular kind of loop known as a for loop. The for loop statement on the third line causes the statements in the following block to be repeated eight times. The number of times it is to be repeated is determined by the stuff between parentheses following the keyword for. The point is that you could, in theory, repeat the same block of statements as many times as you want. The primary purpose of the for loop is to execute a block of statements a given number of times.

In general, a loop has two parts to it: it has a loop body, which is the code that is to be repeated and can be a single statement or a block of statements, and it has a loop control mechanism that determines how many times the loop body should execute. Finally remember that you can always nest loops of one kind within another.

Varieties of Loop

There are four kinds of loop statements you can use. The syntax for a for loop:

1. The Numerical for Loop
The syntax is:

Java Code: Syntax for Numerical for Loop
for (initialization_expression ; loop_condition ; increment_expression) { 
   // statements
}
Execution of this loop continues as long as the condition you specify in the second part of the control mechanism, the loop_condition, is true. This expression is checked at the beginning of each loop iteration, and as long as it is true, the loop body executes. When loop_condition is false, the loop ends and execution continues with the statement following the loop block.

2. The Collection-Based for Loop
The syntax is:

Java Code: Syntax for Collection-Based for Loop
for (type identifier : iterable_expression) { 
   // statements
}
This for loop has two control elements separated by a colon that appear between the parentheses following the for keyword. The first element is an identifier of the type that you specify, and the second is an expression specifying a collection of objects or values of the specified type. The loop executes once for each item of the specified type that appears in the collection, and you can refer to the current item in the loop body using the identifier that you specified as the first control element.

3. The While Loop
The syntax is:

Java Code: Syntax for While Loop
while (expression) { 
   // statements
}
This loop executes as long as the logical expression between the parentheses is true. When expression is false, the loop ends and execution continues with the statement following the loop block. The expression is tested at the beginning of the loop, so if it is initially false, the loop body is not executed at all. An example of a while loop condition might be yesNo=='y' || yesNo=='y'. This expression is true if the variable yesNo contains 'y' or 'y,' so yesNo might hold a character entered from the keyboard in this instance.

4. The Do-While Loop
The syntax is:

Java Code: Syntax for Do-While for Loop
do { 
   // statements
} while (expression);
This loop is similar to the while loop, except that the expression controlling the loop is tested at the end of the loop block. This means that the loop body always executes at least once, even if the expression is always false. The basic logic of each of the four kinds of loop is shown in the figure below:

Tutorial:Review of Java Loops and Logic for the Java Certification Exam-d5-typesofloop.jpg
Figure:Flow for Four Kinds of Loop

The two versions of the for loop have quite different mechanisms controlling the number of iterations. You can also see quite clearly that the primary difference between the while loop and the do-while loop is where the test is carried out.

Counting Using Floating-Point Values

You can use a floating-point variable as the loop counter in a for loop if you need to. This may be needed when you are calculating the value of a function for a range of fractional values. Suppose you want to calculate the area of a circle with values for the radius from 1 to 2 in steps of 0.2. You could write this as

Java Code:
for(double radius = 1.0 ; radius <= 2.0 ; radius += 0.2) { 
   System.out.println(“radius = “ + radius + “ area = “ + Math.PI*radius*radius);
}
which produces the following output:

XML Code: Floating Point Counting Output
radius = 1.0 area = 3.141592653589793 
radius = 1.2 area = 4.523893421169302 
radius = 1.4 area = 6.157521601035994 
radius = 1.5999999999999999 area = 8.04247719318987 
radius = 1.7999999999999998 area = 10.178760197630927 
radius = 1.9999999999999998 area = 12.566370614359169
The area has been calculated using the formula πr2 with the standard value PI defined in the Math class, which is 3.14159265358979323846. Although you may have intended the values of radius to increment from 1.0 to 2.0 in steps of 0.2, they don't quite make it. The value of radius is never exactly 2.0 or any of the other intermediate values because 0.2 cannot be represented exactly as a binary floating-point value. Therefore the golden rule for floating point loops is:

When it comes to controlling a loop, never use tests that depend on an exact value for a floating-point variable

The continue Statement

There are situations where you may want to skip all or part of a loop iteration. Suppose you want to sum the values of the integers from 1 to some limit, except that you don't want to include integers that are multiples of three. You can do this using an if and a continue statement:

Java Code: Continue Statement
for(int i = 1; i <= limit; ++i) { 
   if(i % 3 == 0) {
      continue; 				// Skip the rest of this iteration
   }
   sum += i;					// Add the current value of i to sum
}
The continue statement is executed in this example when i is an exact multiple of 3, causing the rest of the current loop iteration to be skipped. Program execution continues with the next iteration if there is one, and if not, with the statement following the end of the loop block. The continue statement can appear anywhere within a block of loop statements. You may even have more than one continue in a loop. Finally there is also a labeled continue statement that you can use to stop executing an inner loop.

Using the break Statement in a Loop

You have seen how to use the break statement in a switch block. Its effect is to exit the switch block and continue execution with the first statement after the switch. You can also use the break statement to break out from a loop. When break is executed within a loop, the loop ends immediately, and execution continues with the first statement following the loop.

The Labeled break Statement

Java also has a labeled break statement. This enables you to jump immediately to the statement following the end of any enclosing statement block or loop that is identified by the label in the labeled break statement. The label precedes the opening brace of the block that it identifies. The figure below illustrates how the labeled break statement works.

Tutorial:Review of Java Loops and Logic for the Java Certification Exam-d5-labeledbreakstatement.jpg
Figure: Labeled Break Statement

The labeled break enables you to break out to the statement following an enclosing block or loop that has an identifying label, regardless of how many levels of nested blocks there are. You might have several loops nested one within the other, for example, where you could use the labeled break to exit from the innermost loop (or indeed any of them) to the statement following the outermost loop. You just need to add a label to the beginning of the relevant block or loop that you want to break out of, and use that label in the break statement.

Using Assertions

When you want to confirm that a certain condition is being meant before continuing with the execution of a method, we use an assertion. A simple assertion is a statement of the form:

Java Code:
assert logical_expression;
Here, assert is a keyword, and logical_expression is any expression that results in a value of true or false. When this statement executes, if logical_expression evaluates to true, then the program continues normally. If logical_expression evaluates to false, the program is terminated with an error message starting with:

Java Code:
java.lang.AssertionError
This is followed by more information about where the error occurred in the code. When this occurs, the program is said to assert. Suppose you have a variable of type int that stores the number of days in the current month. Assuming the daysInMonth is valid, the listing below shows what this would look like:

Java Code:
if(daysInMonth == 30) { 
   System.out.println(“Month is April, June, September, or November”);
} else if(daysInMonth == 31) { 
   System.out.println(“Month is January, March, May, July, August, October, or December.”);
} else if(daysInMonth == 28 || daysInMonth == 29) { 
   System.out.println(“Month is February.”);
} else { 
   assert false;
}
Here, if daysInMonth is valid, the program should never execute the last else clause. An assertion with the logical expression as false always asserts and terminates the program.

More Complex Assertions

There is a slightly more complex form of assertions that have this form:

Java Code: Complex Assertion Syntax
assert logical_expression : string_expression;
Here, logical_expression must evaluate to a boolean value, either true or false. If logical_ expression is false then the program terminates with an error message including the string that results from string_expression.

Summary

In this chapter you have learned about all of the essential mechanisms for making decisions in Java. You have also learned all of the looping facilities that you have available when programming in Java. You will use all of these capabilities in examples throughout the rest of the book.