|
If expressions are the meat of programming, than I suppose that loops and other control statements are the recipes for using the meat. (Maybe that's taking the analogy a bit too far.) Control statements tell Java what to do when. They bring order and reason to a program and help avoid repeating code.
Generally speaking, a control statement is a statement that directs the execution of other statements. More specifically, a selection statement is one that tells Java which statement should be executed, depending on the evaluation of an expression. A loop statement is one that doubles back on itself, repeating the same statements over and over until a certain condition is met.
There are five main types of control statements used in Java:
| Name |
Form |
Type |
| if |
if (expression) statement;
OR
if (expression) statement;
else statement; |
selection |
| while |
while (expression) statement; |
loop |
| do-while |
do statement while (expression); |
loop |
| for |
for (initialization; condition; increment)
statement; |
loop |
| switch |
switch (expression) {
case value1:
statement1;
break;
case value2:
statement2;
break;
...
default:
defaultStatement;
} |
selection |
Don't worry if these don't make sense yet. We'll be going into each one individually. So, let's begin.
|