There are three main types of flow controls. The if...else statements, the switch statements, and the do…while statements which I have already discussed in the loops tutorial. Probably the most common is the if…else statement which you learn about in junior high school.
The basic idea behind the if statement is
Code:
Code:
if(true){
//evaluate code
} Which is absolutely necessary if you want your program to make any decisions. Between the parentheses a Boolean statement is evaluated, if it is true it will evaluate the code, in this example if it is false it will totally ignore it. What is a Boolean statement you ask? A Boolean statement can be written using any logical operator. For example:
Code:
Code:
int x = 0;
if(x == 0){
//evaluate code
} Will evaluate the code. Java also has the cabapility to evaluate code if the if statement is false. To do that you will use the else clause.
Code:
Code:
int x = 1;
if(x == 0){
//evaluate code
}else {
//evaluate code
} In this case, when the if statement is evaluated, it returns false and then the else code is executed. To allow even more flexibility, Java has an else if statement also.
Code:
Code:
int day = 2;
if(day == 1){
System.out.println(“Monday”);
}else if(x == 2 {
System.out.println(“Tuesday”);
} else {
//evaluate code
} Although this is extremely useful, depending on what you need to do, there is a more efficient way, the case/switch mechanism. For the example above, to write five more else if statements would work to determine the day of the week but it could be more efficient to create something like this:
Code:
Code:
int day = 2;
switch (day) {
case 1: System.out.println("Monday"); break;
case 2: System.out.println("Tuesday"); break;
case 3: System.out.println("Wednesday"); break;
case 4: System.out.println("Thursday"); break;
case 5: System.out.println("Friday"); break;
case 6: System.out.println("Saturday"); break;
case 7: System.out.println("Sunday"); break; }