It would be a poor computer language that didn’t offer the ability to change course based on conditions. Here are those you’ll find in Java. All of them depend on conditional expressions as discussed in Lesson 2, continued: Java Expressions and Operators.
return
The return statement exits a method. It’s required for methods that return values, and optional for those that don’t. We discussed this further in lesson 4.
if/then
Long before it was a Broadway musical, the if/then construct was a feature of every high-level programming language. Its format is like this:
if (<conditional-expression>) {
...
} else {
...
}
Notice that the conditional expression is enclosed in parentheses (but not the < and >–they’re just there for illustration). Following that is a block of statements, enclosed in braces, to be executed if the condition is true; then, optionally, the word else and a block of statements, enclosed in braces, to be executed only if the condition is false. Simple!
if statements may be nested. But keep nesting to a minimum, lest you end up with a mess that looks like this:
if (a == b) {
if (c == d && pigsCanFly) {
if (e > f) {
System.out.println("Hello");
} else {
System.out.println("Goodbye");
} else {
a = a + 1;
}
} else if (q != z) {
b = b - 20;
}
while and do-while
Often you want to repeat a block of code as long as a particular condition is true. For this we have the while construct:
while (<conditional-expression>) {
...
}
If the conditional expression is false at the outset, the block inside the braces doesn’t execute. On the other hand, make sure to make the conditional expression false somewhere inside the braces; otherwise, the loop will never end!
The companion to while is do-while. It looks like this:
do {
...
} while (<conditional-expression>)
The difference is that in while, the condition is tested before the block executes; in do-while, it’s tested after the block executes–and is thus guaranteed to execute at least once.
switch
The switch statement chooses one or more blocks to be executed based on the value of an expression.
switch (month) {
case 1:
System.out.println("January");
break;
case 2:
System.out.println("February");
case 3:
System.out.println("March");
break;
default:
System.out.println("Something else");
}
In the example above, month is evaluated at the start of the statement. If its value is 1, “January” is displayed. If the value is neither 1, 2, nor 3, the program displays “Something else”.
If the value is 2, both “February” and “March” are displayed. Why? It’s because there’s no break statement after the statement that displays “February!” Once a case matches, all statements in the remaining cases in the switch statement are executed until a break appears–even though the associated case doesn’t apply. Don’t forget the break statement!!!!
switch is especially useful with enums, like this:
public class Switch {
public static enum Stooge {
LARRY, MOE, CURLY
}
public static void main(String[] args) {
Stooge stooge = Stooge.CURLY;
switch (stooge) {
case CURLY:
System.out.println("Nyuk! Nyuk! Nyuk!");
case LARRY:
System.out.println("I'm Larry");
case MOE:
System.out.println("I'm Moe");
default:
System.out.println("Nobody home");
}
}
}
Notice that the values in the cases don’t need to be qualified; it’s obvious from the value being tested that it’s a Stooge. Also, if you press Ctrl+Space after typing “case,” Eclipse’s code completion will offer you the remaining values of Stooge as possible test values.
for
We’ve already seen the for/each construct in Lesson 5, where we processed each element of an array or List like this:
Integer[] arrayOfIntegers = {0, 1, 2, 3};
for (Integer someInt : arrayOfIntegers) {
...
}
Now we’ll look at another form of for. As W3Schools says, the for statement is used when you know how many times you want to execute a block of code (as opposed to while, where you don’t). It’s format is:
for (statement 1; condition; statement 2) {
...
}
statement 1
is executed one time at the start of the block. From then on, if the condition
is still true, the block is executed and then statement 2
is executed. And the block repeats as long as condition
remains true. The whole process is called a loop, and a typical for loop looks like this:
for (int i = 0; i < args.length; i++) {
System.out.println(args[i]);
}
Notice how i is incremented at the end of the loop. Once it reaches the length of args, the loop will stop. (Notice, too, that statement 2
isn’t followed by a semicolon.)
By the way, there’s no reason the value of i can’t start at a maximum and work its way backward. Nor need the value increase by 1 each time–you might add a larger increment. Also, the components of the for needn’t manipulate a value at all, though I can’t see how. Finally, with code completion, you can type for followed by Ctrl+Space and Eclipse will offer you a selection of for statement syntaxes.
break and continue
Remember Edsger Dijkstra from Lesson 2: Elements of a Java Class? Well, when not taking digs at both object-oriented programming and the great State of California, he made a significant contribution to computer science in his landmark letter, “Go To Statement Considered Harmful.” Every high-level computer language since its publication in 1968 has been missing one kind of statement: “GO TO,” which in languages like COBOL allowed branching to any other part of a program without returning. This allowed for chaos when used injudiciously (which it often was).
Even so, in more modern languages, it’s not true that the flow of execution never skips over statements. It’s just that the only places you can skip to are the spot immediately following the current block of code, or to the next iteration of that block of code.
The statements that provide this ability are break and continue. break gets you out of a code block; you’ve already seen this in the discussion of the switch statement above. continue skips to the end of a repeating code block and continues with the next iteration.
For example:
public class BreakAndContinue {
public static void main(String[] args) {
char[] letter = {'a', 'b', 'c', 'd', 'e'};
for (int i = 0; i < letter.length; i++) {
if (letter[i] == 'b') {
continue;
}
if (letter[i] == 'd') {
break;
}
System.out.println(letter[i]);
}
}
}
… displays this result on the console:
a
c
When letter[i]
is ‘b’, the continue statement causes execution to jump to the bottom of the loop and start the next iteration. When letter[i]
is ‘d’, the break statement causes execution to leave the loop altogether.
What You Need To Know
- Java has several flow control statements:
- return
- if/then
- while
- do/while
- switch
- for
Next, sounding the alarm: Exceptions