2.0 Learn to Code JAVA: Control Statements 

6 Control Structures — Loops & Branch Statements 

SHAZ
18 min readJan 9, 2014

Notes From Chapter 3: Programming in the Small II: Control

What are Control Structures?

Control structures control the flow of the program. That is, how the program will evaluate, test statements and execute code according to the desired result.

In “programming in small” there are two types of control structures, loops and branches that can be used to repeat a sequence of statements over and over or to choose among two or more possible courses of action.

In Java, there are just six such structures that are used to determine the normal flow of control in a program. They are: the block, the while loop, the do..while loop, the for loop, the if statement, and the switch statement.

Each of these structures are considered to be a single “statement”, but each is in fact a structure statement that can contain one or more other statements inside itself.

The ability for a computer to perform complex tasks is built on just a few ways of combining simple commands into control structures.

1. Block Statement

The block is the simplest type of structured statement. Its purpose is simply to group a sequence of statements into a single statement. The format of a block is:

{

(statements)

}

The block consists of a sequence of statements enclosed between a pair of braces, “{“ and “}”.

It is possible for a block to contain no statements at all; such a block is called an empty block, and can actually be useful at times. An empty block consists of nothing but an empty pair of braces.

How to use Block Statements?

Block statements usually occur inside other statements, where their purpose is to group together several statements into a unit.

  1. A block can be legally used wherever a statement can occur.
  2. One place where a block is required is in the main method of a program: the definition of a method is a block, since it is a sequence of statements enclosed inside a pair of braces.
  3. You should lay out your program on the page in a way that will make its structure as clear as possible. This means putting one statement per line and using indentation to indicate statements that are contained inside control structures.
  4. A variable declared inside a block is completely inaccessible and invisible from outside that block. When the computer executes the variable declaration statement, it allocates memory to hold the value of the variable. When the block ends, the memory is discarded (that is, made available for reuse). The variable is said to be a local to the block.
  5. There is a general concept called the “scope” of an identifier. The scope of an identifier is the part of the program in which that identifier is valid. The scope of a variable defined inside a block is limited to that block, and more specifically to the part of the block that comes after the declaration of the variable.

2. While Loop

The block statement by itself really doesn't after the flow of control structure, the five remaining control structures do. They can be divided into two classes: loop statements and branching statements.

Let’s focus on the first of three loops in Java, the While Loop.

You really just need one control from each category (the structure control statements) in order to have a completely general-purpose programming language.

How it looks?

A while loop is used to repeat a given statement over and over, but only so long as a specified condition remains true. A while loop has the form:

While ( Boolean-expression ) {

(statements)

}

The braces should always be included as a matter of style, even when there is only one statement between them.

The (Statement) can be a block statement consisting of several statements grouped together between a pair of braces. This statement is called the body of the loop.

The body of the loop is repeated as long as the (Boolean-expression) is true. This Boolean expression is called the continuation condition, or more simple the test, of the loop.

What happens if the condition is false in the first place, before the body of the loop is executed even once? In that case, the body of the loop is never executed at all. The body of a while loop can be executed any number of times, including zero.

What happens if the condition is true, but it becomes false somewhere in the middle of the loop body? Does the loop end as soon as this happens? It doesn't, because the computer continues executing the body of the loop until it gets to the end. Only then does it jump back to the beginning of the loop and test the condition, and only then can the loop end.

How it works?

Semantics of the while go like this: When the computer comes to a while statement, it evaluates the ( Boolean-expression ), which yields either true or false as its value. If the value is false, the computer skips over the rest of the while loop and proceeds to the next command in the program. If the value of the expression is true, the computer executes the (statement) or block of (statements) inside the loop. Then it returns to the beginning of the while loop and repeats the process. That is, it re-evaluates the ( Boolean-expression), ends the loop if the value is false, and continues it if the value is true. This will continue over and over until the value of the expression is false; if that never happens, then there will be an infinite loop.

By the way, you should remember that you’ll never see a while loop standing by itself in a real program. It will always be inside a method which is itself defined inside some class.

Additional Note

Priming the Loop: We have to do something before the while loop to make sure that the test makes sense. Setting things up so that the test in a while loop makes sense the first time it is executed is called priming the loop.

3. The do…While Statement

Sometimes it is more convenient to test the continuation condition at the end of a loop, instead of at the beginning, as is done in the while loop. The do…while statement is very similar to the while statement, except that the word “while”, along with the condition that it tests, has been moved to the end. The word “do” is added to mark the beginning of the loop.

How it looks?

Do {

(Statement)

} While (Boolean-expression);

Note the semicolon, ‘;’ at the very end. The semicolon is part of the statement, just as the semicolon at the end of an assignment statement or declaration is part of the statement. Omitting it is a syntax error.

How it works?

To execute a do…while loop, the computer first executes the body of the loop — that is, the statement or statements inside the loop — and then it evaluates the Boolean expression.

If the value of the Boolean expression is true, the computer returns to the beginning of the do loop and repeats the process; if the value is false, it ends the loop and continues with the next part of the program.

When a value of the Boolean variable is set to false, it is a signal that the loop should end. When a Boolean variable is used in this way — as a signal that is set in one part of the program and tested in another part — it is sometimes called a flag or flag variable (in the sense of a signal flag)

Since the condition is not tested until the end of the loop. The body of a do loop is always executed at least once.

Although a do…while statement is sometimes more convenient than a while statement, having two kinds of loops does not make the language more powerful. Any problem that can be solved using do…while loops can also be solved using only while statements, and vice versa.

Break; & Continue; Statement

Break Statements

The syntax of the While Loop and Do…While Loops allows you to test the continuation condition at either the beginning of a loop or at the end. Sometimes, it is more natural to have the test in the middle of the loop, or to have several tests at different places in the same loop.

Java provides a general method for breaking out of the middle of any loop. It’s called the break statement, which takes the form: break;

How it works?

When the computer executes a break statement in a loop, it will immediately jump out of the loop. It then continues on to whatever follows the loop in the program.

Remember, the condition in a while loop can be any Boolean-valued expression i.e. while (true). So the computer evaluates this expression and checks whether the value is true or false. The Boolean literal “true” is just a Boolean expression that always evaluates to true.

So “while (true)” can be used to write an infinite loop, or one that will be terminated by a break statement. A break statement terminates the loop that immediately encloses the break statement.

How to break; from nested loops?

It is possible to have nested loops, where one loop statement is contained inside another [more information on nesting below]. If you use a break statement inside a nested loop it will only break out of that loop, not out of the loop that contains the nested loop.

There is something called a labelled break statement that allows you to specify which loop you to break.

Labels work like this: You can put a label in front of any loop. A label consists of a simple identifier followed by a colon.

For example, a while with a label might look like this, mainloop: while…Inside this loop you can use the labelled break statement, “break mainloop;” to break out of the labelled loop.

Continue Statements;

Continue statements are related to break, but less commonly used.

A Continue statement tells the computer to skip the rest of the current iteration of the loop. However, instead of jumping out of the loop altogether, it jumps back to the beginning of the loop and continues with the next iteration (including evaluating the loop’s continuation condition to see whether any further iterations are required.

As with a break, when a continue is in nested loop, it will continue the loop that directly contains it; a “labelled continue” can be used to continue the containing loop instead.

Break and Continue can be used in while loops and do…while loops. Break can also be used to break out of a switch statement.

A break can occur inside an If statement, but in that case, it does not mean to break out of the if. Instead, it breaks out of the loop or switch statement that contains the If statement. If the if statement is not contained inside a loop or switch, then the if statement cannot legally contain a break. A similar consideration applies to continue statement inside ifs.

4. For Statement

For certain type of problems, for loops can be easier to construct and easier to read than the corresponding while loop. It’s quite possible that in real programs, for loops actually outnumber while loops.

How it looks?

For (initialization); (continuation-condition); (update); {

(Statements)

}

Example of a For Loop

Here is a counting for loop in which the loop control variable, years, takes on the values 1, 2, 3, 4, 5.

For (years = 0; years < 5; years++) {

Interest = principal * rate;

Principal = principal + interest;

System.out.println(principal);

}

How it works?

For above example, it is seen that the initialization, continuation and updating have all been involved in the “control” of the loop in one place, which helps make the loop easier to read and understand.

The for loop is executed in exactly the same way as the original code: The initialization part is executed once, before the loop begins. The initialization is usually a declaration or an assignment statement, but it can be any expression statement that would be allowed as a statement in a program.

Usually, the initialization part of a for statement assigns a value to some variable, and the update changes the value of that variable with an assignment statement or an increment or decrement statement.

The continuation condition is executed before each execution of the loop, and the loop ends when this condition is false. The continuation-condition must be a Boolean-valued expression.

The update part is executed at the end of each execution of the loop, just before jumping back to check the condition again. The update can be any expression statement, but is usually an increment, a decrement, or an assignment statement.

Any of the three [initialization, continuation-condition and update] can be empty. If the continuation statement is empty, it is treated as if it were “true”, so the loop will be repeated forever or until it ends for some other reason, such as a break statement.

Loop Control Variable

What is a loop control variable? When value of the variable is tested in the continuation condition and the loop ends when this condition evaluates to false.

In for statement example given above, the loop control variable is years.

Counting for Loop

Certainly, the most common type of for loop is the counting loop, where a loop control variable takes on all integers values between some minimum and some maximum value. A counting loop has the form:

For (<variable> = <min>; <variable> <= <max>; <variable>++) {

Statements

}

Here the <min> and <max> are integer-valued expressions (usually constants). The <variable> takes on the values <min>, <min>+1, <min>+2,…., <max>.

The value of the loop control variable is often used in the body of the loop.

Simpler example, in which the numbers 1, 2…., 10 are displayed on the standard output:

for ( N = 1 ; N < 10 ; N++ )

System.out.println( N );

Did you know? The official syntax of for statement actually allows both the initialization part and the update part to consist of several expressions, separated by commas. So we can even count up from 1 to 10 and count down from 10 to 1 at the same time!

for ( i=1, j=10; i <=10; i++, j— ) {

System.out.print(“%5d”, i); // Output I in a 5-character wide column

System.out.println(“%5d”, j); // Output j in a 5-character column.

System.out.println(); // and end the line.

}

Additionally

· It is worth stressing one more time that a For loop statement, like any loop statement, never occurs on its own in a real program.

· A statement must be inside the main method of a program or inside some other method. And that method must be defined inside a class.

· I should also remind you that every variable must be declared before it can be used, and that includes the loop control variable in for statement.

· Also, it is not required the loop control variables be declared type int.

Enums and “for-each” Loop

A data structure is a collection of data items, considered as unit. For example, a list is a data structure that consists simply of a sequence of items.

The enhanced for loop makes it easy to apply the same processing to every element of a list or other data structure.

“Since the intent of the enhanced for loop is to do something “for each” item in a data structure, it is often called a ‘for-each’ loop.”

One of the applications of the enhanced for loop is for enum types. The enhanced for loop can be used to perform the same processing on each of the enum constants that are the possible values of an enumerated type.

The syntax for doing this:

For ( <enum-type-name> <variable-name> : <enum-type-name>.values() ) {

Statements

}

It’s helpful to think of the colon ‘:’ in the loop as meaning “in”.

If MyEnum is the name of any enumerated type, then MyEnum.values() is a function call that returns a list containing all of the values of the enum. Values() is a static member function in MyEnum and of any other enum. For this enumerated type, the for loop would have the form:

For ( MyEnum <variable-name> : MyEnum.values() ) {

Statements

}

How for loops work for enumerated types?

The intent of this is to execute the <statement> once for each of the possible values of the MyEnum type.

The <variable-name> is the loop control variable. This variable should not be declared before the for loop; it is essentially being declared in the loop itself.

In the <statement>, it represents the enumerated type value that is currently being processed.

Example of a “For Loop” to enumerated types data

To give a concrete example, suppose that the following enumerated type has been defined to represent the days of the week:

enum Day { MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY }

Then we could write:

for ( Day d : Day.values() ) {

System.out.print( d );

System.out.print(“ is day number “);

System.out.println( d.ordinal() );

}

Day.values() represents the list containing the seven constants that make up the enumerated type.

The first time through this loop, the value of ‘d’ would be the first enumerated type value Day.MONDAY, which has ordinal number 0, so the output would be “MONDAY is day number 0".

The second time through the loop, the value of d would be Day.TUESDAY, and so on through Day.SUNDAY.

The body of the loop is executed once for each item in the list Day.values(), with d taking on each of those values in turn.

The full output from this loop would be:

MONDAY is day number 0

TUESDAY is day number 1

WEDNESDAY is day number 2

THURSDAY is day number 3

FRIDAY is day number 4

SATURDAY is day number 5

SUNDAY is day number 6

Nested Loops

Control structures in Java are statements that contain statements. In particular, control structures can contain levels of control structures in itself.

One example of this: is a while loop inside another while loop, but any combination of one control structure inside another is possible.

Another example of having multiple levels of nesting is a while loop inside an if statement inside another while loop.

We say that one structure is nested inside another. The syntax of Java does not set a limit on the number of levels of nesting,

As a practical matter, though, it’s difficult to understand a program that has more than a few levels of nesting.

5. If Statement

The first statement of the two branching statements in Java is the If statement.

The IF statement allows you to branch based on the result of a Boolean operation. It is an example of a “branching” or “decision” statement.

How it works?

An If statement tells the computer to take one of two alternative courses of action, depending on whether the values of a given Boolean-valued expression is true or false. The If statement has the form:

If ( Boolean-expression ) {

(statement)

}

Else-If Statement

The way I understand, Else-If statements are a another version of the If Statement that allows the program to choose between doing something and not doing it with an if statement that omits the else part:

If (Boolean-expression) {

(statements)

}

Else {

(statements)

}

What Else-If Statements do?

Basically, when the computer executes an if statement, it evaluates the Boolean expression. If the value is true, the computer executes the first statement and skips the statement that follows the “else”. If the value of the expression is false, then the computer skips the first statement and executes the second one.

Note: One and only one of the two statements inside the if statement is executed.

How it works?

As usual, the statements inside an If statement can be blocks.

The if statement represents a two-way branch. The else part of an If statement — consisting of the word “else” and the statement that follows it — can be omitted.

In the case of having multiple If statements at once, the computer executes one and only one of the three statements for example <statement-1>, <statement-2> or <statement-3> — will be executed.

The computer starts by evaluating <Boolean-expression-1>, if it is true, the computer executes <statement-1> and then jumps all the way to the end of the out if statement skipping the other two <statement>s.

If <Boolean-expression-1> is false, the computer skips <statement-1> and executes the second , nested if statement. To do this, it tests the value of <boolean-expression-2> and uses it to decide between <statement-2> and <statement-3>.

Basically, the computer evaluates Boolean expressions one after the other until it comes to one that is true. It executes the associated statement and skips the rest. If none of the Boolean expressions evaluate to true, then the statements in the else part is executed.

This statement is called a multi-way-branch because only of the statements will be executed. The final else part can be omitted. In that case, if all the Boolean expressions are false none of the statements are executed

Of course, each of the statements can be a block, consisting of a number of statements enclosed between { and }.

The Empty If Statement

Another type of statement in Java: the empty If statement. This is a statement that consists simply of a semicolon and which tells the computer to do nothing.

The existence of the empty statement makes the following legal, even though you would not ordinarily see a semicolon after a }.

How it looks?

if (x < 0) {

x = -x;

};

The semicolon ‘;’ is legal after the }, but the computer considers it to be an empty statement, not part of the if statement.

Occasionally, you might find yourself using the empty statement when what you mean is, in fact, “do nothing”.

For example, the rather contrived if statement:

If ( done )

; // Empty statement

Else

System.out.println(“Not done yet.”)

Does nothing when the Boolean variable “done” is true, and prints out “Not yet done” when it is false. You can’t just leave out the semicolon in this example, since Java syntax requires an actual statement between the if and the else.

It is preferred, though, to use an empty block, consisting of { and } with nothing between, for such cases.

Occasionally, stray empty statements can cause annoying, hard-to-find errors in a program. For example: the following program segment prints “Hello” just once not ten times:

for (int i=0; i<10; i++);

System.out.println(“Hello”);

Why? Because the “;” at the end of the first line is a statement, and it is this statement that is executed ten times.

The System.out.println statement is not really inside the for statement at all, so it is executed just once, after the for loop has completed.

6. Switch Statement

The second branching statement in Java is the switch statement, which is introduced in this section.

The switch statement is used far less often than the if statement, but it is sometimes useful for expressing a certain type of multi-way branch.

How it looks?

Switch (<expression>) {

Case <constant-1> :

<statements-1>

Break;

Case <constant-2> :

<statement-2>

Break;

.

. // (more cases)

.

Case <constant-N> :

<statement-N>

Break;

Default: //optional default case

<statements-(N+1)>

} // end of switch statement.

How it works?

A switch statement allows you to test the value of an expression and, depending on that value, to jump directly to some location within the switch statement.

Only expressions of certain types can be used. The value of the expression can be one of the primitive integer type int, short byte or char type and enumerated type (strings are also allowed in Java 7). The expression cannot be a real number.

The positions that you can jump to are marked with case labels that take the form : “case <constant>:”. This marks the position the computer jumps to when the expression evaluates to the given <constant>.

As the final case in a switch statement you can, optionally, use the label “default:”, which provides a default jump point that is used when the value of the expression is not listed in any case label.

Break statements in Switch Statements

The break; statements are technically optional.

The effect of a break; is to make the computer jump to the end of the switch statement. If you leave out the break statement, the computer will just forge ahead after completing one case and will execute the statements associated with the next case label. This is rarely what you want, but it is legal.

Side Note: The break statement inside a method (subrountine) is sometimes replaced by a return statement.

You can leave out one of the groups of statements entirely (including break). So you then have two case labels in a row, containing two different constants. This just means that the computer will jump to the same place and perform the same action for each of the two constants.

Note: Constants in the label case don’t have to be in any particular order, as long as they are all different.

The switch statement is pretty primitive as control structures go, and it’s easy to make mistakes when you use it.

Java takes all its control structures directly from the older programming languages C and C++. The switch statement is certainly one place where the designers of Java should have introduced some improvements.

Menus and Switch statements

One application of switch statements is in processing menus.

A menu is a list of options. The user selects one of the options. The computer has to respond to each possible choice in a different way.

If the options are numbered 1,2…3, then the number of the chosen option can be used in a switch statement to select the proper response.

Second set of notes in a series of post I’ll be publishing as I self-teach myself how to code in Java. For a full-background story read this.

Disclaimer: I’m not an expert, still learning. So if any programmer out there wants to express their opinion, correct or add to these notes please feel free to do so in the comments.

The sole purpose for publishing these notes is to inspire someone who is thinking about learning to code and wants to get a feel for the subject before diving straight in.

Thank You.

Notes Extracted From Are Credited to: Textbook Introduction to Programming Using Java, Sixth Edition Author: David J. Eck.

--

--