Control Structures
Don’t let the name scare you; control structures aren’t as complicated as they sound! Both of the simple programs and all of the examples we’ve seen so far have had one thing in common: they’ve executed in a straight line, a statement at a time, from top to bottom. In simple terms, control structures let you break out of that straight-line mould, allowing your programs to react differently to different conditions and saving you some typing when performing repetitive tasks.
Let’s start with the most basic control structure, an if
statement:
if (condition) statement;
If the condition
is true, then Java will execute the statement
. If not, nothing happens and Java just moves on to the next line of the program. Here’s a simple example:
// Check if a and b are equal
boolean abEqual = (a == b);
if (abEqual) System.out.println("a and b are equal!");
This is the practical application of the comparison operators that I promised above! The first line of the above (after the comment) checks ifa
andb
are equal (that is, if they contain the same value). If they are,abEqual
is assigned a value of true. If not,abEqual
is set to false. On the second line, we have anif
statement that usesabEqual
as its condition. As you can see, ifa
andb
are equal (and thusabEqual
is true), the program prints out a message to that effect. If not (andabEqual
is false), then nothing happens.Since most conditions are only used once, it is more common to type the conditional expression directly in the
if
statement, instead of using a variable. Here's how the above example would normally look:
// Check if a and b are equal
if (a == b) System.out.println("a and b are equal!");
As always, use whichever method you are most comfortable with. Here are a few more examples of comparison operators in action as part ofif
statements:
if (a > b) System.out.println("a is greater than b");
if (a < b) System.out.println("a is less than b");
if (a >= b) System.out.println("a is greater than or equal to b.");
if (a <= b) System.out.println("a is less than or equal to b.");
if (a != b) System.out.println("a does not equal b");
Instead of a single statement, you can specify a whole series of statements that should be executed if the condition is true. You do this by putting the statements between braces:
if (userIsKevin) {
System.out.println("Hi, Kevin!");
// ... more statements here ...
}
If you want to do something when a condition is false instead of when it is true, there is a handy shortcut you can use. Here’s how the code might look without using the shortcut:
// Print message when myCondition is false
if (myCondition == false) {
System.out.println("myCondition is false!");
}
The ==
operator (and the !=
operator) can be used on boolean
values as well as numeric types. As a result, the condition above will be true when myCondition
is false, and false when myCondition
is true. The shortcut I mentioned involves something called the negation operator. By placing this operator (!
, an exclamation mark) before a variable name or before a set of parentheses containing an expression, the value of that variable or expression will be flipped from true to false (and vice versa). Thus, the above example could be more simply written as follows:
// Print message when myCondition is false
if (!myCondition) {
System.out.println("myCondition is false!");
}
If myCondition
is true, the !
operator will cause the condition to evaluate to false so the message will not be printed. If myCondition
is false, the !
flips the expression’s value to true and the message does get printed. It’s important to note that the !
operator doesn’t actually change the value that is stored in myCondition
; it just alters the value of the condition for the purposes of the if
statement.
Another control structure that is related to the if statement is the if-else
statement:
if (condition) {
// statements to be executed if condition is true
}
else {
// statements to be executed if condition is false
}
In this case, one group of statements or the other will be executed. The condition determines which. Each of the bracketed sets of statements could also be a single statement instead. In fact, by using another if-else
statement in place of the second bracketed block of statements, you can test multiple conditions and perform an action depending on which of the conditions is true:
if (condition1) {
// do this if condition1 is true
} else if (condition2) {
// do this if condition2 is true
} else if (condition3) {
// do this if condition3 is true
} else {
// do this only if none of the conditions is true
}
This code structure may be a little overwhelming at first glance, but reading it aloud helps to make its operation pretty self-evident. Here’s the code above, as it might be expressed in English:
If
condition1
is true, execute the first block of statements. Otherwise, ifcondition2
is true, execute the second block of statements. Otherwise, ifcondition3
is true, execute the third block of statements. Otherwise, execute the final block of statements.
The rest of the control structures that I’ll discuss in this article have to do with making your program perform the same operation several times without having to type the commands for that operation over and over again. These structures are normally called loops.
Kevin Yank is an accomplished web developer, speaker, trainer and author of Build Your Own Database Driven Website Using PHP & MySQL and Co-Author of Simply JavaScript and Everything You Know About CSS is Wrong! Kevin loves to share his wealth of knowledge and it didn't stop at books, he's also the course instructor to 3 online courses in web development. Currently Kevin is the Director of Front End Engineering at Culture Amp.