Jump to content


Check out our Community Blogs

Register and join over 40,000 other developers!


Recent Status Updates

View All Updates

Photo
- - - - -

Java:Tutorial - Flow Control


  • Please log in to reply
1 reply to this topic

#1 John

John

    CC Mentor

  • Moderator
  • 4450 posts
  • Location:New York, NY

Posted 09 December 2006 - 03:47 PM

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

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:

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.

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.

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:

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;
}

  • 0

#2 Bitterfrost

Bitterfrost

    CC Lurker

  • Just Joined
  • Pip
  • 1 posts

Posted 08 March 2011 - 02:14 PM

Hi,

There is an error in the code:

int day = 2;
if(day == 1){
System.out.println(“Monday”);
}else if(x == 2 {
System.out.println(“Tuesday”);
} else {
//evaluate code
}

}else if(x == 2 has to be }else if(day == 2)
  • 0




Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download