by Dinesh Thakur Category: Control Structures

Different types of control statements: the decision making statements (if-then, if-then-else and switch), looping statements (while, do-while and for) and branching statements (break, continue and return).

Control Statements in java

At the moment we are using sequential programming. It means that our code gets executed from the first line, in order, down to the last line. We call this linear code – Java reads each line from top to bottom.  
We don’t always need this in our programs though; on occasion you might only want a piece of code to be executed if it has met one or more specified conditions.  Let’s say that you want a message to be displayed on the screen if a user is  21 or over, but you want a different one displayed if they are under 21. You need to be able to control the flow of your code, and you can only do that with conditional logic.  
Conditional logic mainly uses the IF word. An example would be IF a user is older than 21, this message will be displayed; IF the user is younger than 21, a different message is displayed. It sounds complicated, but conditional logic is very  easy to use.  
The control statement are used to controll the flow of execution of the program . This execution order depends on the supplied data values and the conditional logic.
The following types of control statements in java

Selection statements in java

The IF Statement

It is a control statement to execute a single statement or a block of code when the given condition is true, and if it is false, then it skips if block and rest code of a program executed.
The IF Statement  One common thing we do in programming is to execute some code when something happens rather than something else happening. It was because of this that  the IF statement came about and this structured like this:  
if ( Statement ) {  }  
We start the statement with IF but note that it is between a set of parentheses and is in lower-case. Curly brackets are then used to section off a piece of code that executes only if a certain condition has met. We place that condition in between the set of parentheses:
if ( user < 21 ) {  }   
Our condition is stating that “if the user is less than 21”. Note that we use shorthand symbols here and not the actual words “is less than.” The symbol for less  than is < so our code is saying that, if the users are less than 21, something happens (a message is displayed):  
if ( user < 21 ) {  //DISPLAY THIS MESSAGE  }  
So, if our user is 21 or older, Java skips the code we inserted in the curly brackets and continues with the rest of the program to the end. The code that we put in the curly brackets only executed if the IF condition, the one input between the parentheses, is met.
Before we turn our hands to this, there is another shorthand symbol to be aware of  - >. This one indicates greater than and it can be used to make a change to the code to check for users older than 21.
if ( user > 21 ) {  //DISPLAY THIS MESSAGE  }  
All we have added to our code is a > symbol; the condition between the parentheses now check if a user is older than 21. 

What it won't check for is those users who are 21; only those that are older. If we  needed to check if a person was 21 or older, we would need to use “greater than or  the same as (equal to) and in programming we can do this using just two symbols  - >=:  
if ( user >= 21 ) {  //DISPLAY THIS MESSAGE  }  
In much the same way, we can check to see if users are 21 or younger by using the symbols for “less than or the same as (equal to).” Those symbols are <=:  
if ( user <= 21 ) {  //DISPLAY THIS MESSAGE  }  
All we did was added < and =.  
Let’s put it all together in one program. First, close down your open program and save it. Start a new project (you know how to do that now) and name your package conditional logic and your class IF Statements. Now you can add this code to the  program:

Decision making statements in java with examples

public class IFStatements {
        public static void main(String[] args){
               int user =20;
               if(user <21)  {
                     System.out.println("User is less than 21");
               }
        }
}

What we did was create an int variable with a value of 20. Our IF statement is going to look for “less than 21” and print the message that is inside curly brackets.  Run this and see what happens.
NetBeans will run the program using bold text in the Project window, rather than the code that you displayed. If you want to run the code in the coding window,  right-click on the code and chose Run File – you now see the output in your  Output window.  
The next thing we do is change the value for the user variable to 21 from 20 and then run it again.  The program should run correctly without any errors, but you won't see anything printed. Why? Because the message to be displayed in inside the IF statement curly brackets and the IF statement is searching for values that are less than 21. If that condition cannot be met, Java ignores the curly brackets and anything in between them, going on to the next section of code.

The IF…ELSE Statement 

You could use two IF statements in your code, but you could also use an IF…ELSE  statement; The if else java statement is an extension of if statement that provides another option when 'if' statement evaluates to "false," i.e., else blocks executed if "if" statement is false. That statement structured like this:  

if ( condition_to_test ) {  }  else {  }  

The same as the IF statement, our line starts with if followed by a set of parentheses that contains the condition that we want to test.  Again, the curly brackets used for sectioning the code into the choices that we want to use; the second follow the ELSE part of the statement and have its curly brackets.  Let’s look at the code we used for checking the age of user:

if else statement in java example program

public class IFELSEStatements {

publicstatic void main(String[] args) {
    int user =20;
    if(user <=21) { 
         System.out.println("User is 21 or younger");
    }
    else {
        System.out.println("User is older than 21");
    }
}

The IF…ELSE IF Statement

The IF…ELSE IF Statement  You can test more than two choices if you want. Let’s say, for example, that we wanted to test for several different age ranges, like 20 to 40, 4 and over, etc., If we have more than two choices, we can use the IF…ELSE IF statement and that structured like this:  
if ( condition_one ) {  }  else if ( condition_two ) {  }  else {  } 
The addition here is:  
else if ( condition_two ) {  }  
The initial IF statement tests the first condition. It followed by the ELSE IF part of the statement with a set of parentheses after it. Between these parentheses is the second condition to test. The final ELSE catch anything not caught by the first two parts of the statement. Once again, curly brackets are used to section our code and each part of the statement, the IF, ELSE IF and ELSE, each has their own set. If any of these bracket sets omitted, an error message is thrown up.  
Before we move on to any more code, it's worth looking at some of the conditional operators in java. We already used these four:  
• which means greater than  
• < which means less than  
• >= which means great than or the same as (equal to)  
• <= which means less than or the same as (equal to)  
There are four more that you can make use of:  
• && which means AND  
• || which means OR  
• == which means HAS A VALUE OF
• ! which means NOT
The first one, indicated by the two ampersands (&) used when you want to test at least two conditions at the same time. We’ll use it to test two age ranges:  else if ( user > 21 && user < 50 ).
We want to see if our user is over 21 but younger than 50 – don’t forget that we are looking to see what’s in the user variable. Condition one checks to see if a user is  21 or older while condition two checks to see if they are younger than 50.  In between these conditions we the && (AND) operator so what this line says is check to see if the user is over AND under 50.   
Before you look at the rest of the conditional operators, try this code:

Control Statements in java with example program

publicclass IFELSEIFStatements {
       publicstaticvoid main(String[] args){
           int user =21;
           if(user <=21){
                System.out.println("User is 21 or younger");
           }
           elseif(user >21&& user <50){
                   System.out.println("User is between 19 and 49");
           }
           elseif(user >50){
                 System.out.println("User is older than 50");
           }
}

The Nested IF Statement 

We can nest IF statements as well as nesting IF…ELSE and the IF…ELSE IF statements. Nesting is just the act of placing one IF statement inside another. Let’s assume that you want to test if a user is less than 21 but older than 18; you need a  message to be displayed for any user who is older than 18, so the first statement is needed:

if ( user < 21 ) {
     System
.out.println("21 or younger");
}

To see if the user is older than 18, we need another IF statement and this can be  placed, or nested, within the first one, like this: 

if ( user < 21 ) {
       if( user >18&& user <21){
            System.out.println("You are 19, 20 or 21");
       }
}

Our first  IF statement catches the user variable if the value is lower than 21 and the second IF statement brings things down to users between 18 and 21. If you wanted something else printed, you would replace the IF statement with an IF…  ELSE statement: 

if ( user < 21 ) {
    if( user >18&& user <21){
         System.out.println("You are 19, 20 or 21");
    }
    else{
         System.out.println("18 or younger");
    }
}

Look at the placement of the curly brackets carefully; put one in the wrong place or forget to put one in and your code isn’t going to run. The nested IF statement might seem a little tricky to get the hang of, but all you are doing is narrowing down your choices.

Boolean Values 

With a Boolean value, there are only two possible outputs – TRUE or FALSE, 1 or 0,  YES or No. In Java, there is a specific variable for these values:  
boolean user = true;  
Rather than using a double, int or string variable, we type boolean (note the lowercase b) and, after the name of the variable, a value assigned, either TRUE or  FALSE. We have used = here as an assignment operator but, if you wanted to know if a variable had a “value of,” you would use two = signs.  
Try this:

boolean user = true;
if ( user == true) {
       System.out.println("it is true");
}
  else {
      System.out.println("it is false");
  }

With our first IF statement, we want to check if the user variable has TRUE value and, with the ELSE part of the statement, we want to see if that value is FALSE.  We don’t need to say ELSE IF (user==false) because, quite simply, what is not true must be false. All we need is ELSE because, as I said earlier, a Boolean have just two values.  
The last conditional operator to use is NOT, and we can use this with Boolean values. Have a look at this example:

boolean user = true;
if ( !user ) {
     System.out.println("it is false");
}
else {
      System.out.println("it is true");
}

Except for one line, it is virtually identical to the previous Boolean code  example – that line is:

if ( !user ) { 

Here, we used the NOT conditional operator just before the user variable; an exclamation mark indicates the operator, placed just before the variable that you want to be tested: the NOT operator test for the opposite of the real value, i.e., negation. We set our user variable as TRUE, so the NOT operator check for FALSE  values. It also works the opposite way around. Think of it this way, if it is NOT  TRUE is has to be FALSE and vice versa.

Switch Statement

One more way we can use to control statement flow is with a switch statement. The keyword "switch" is followed by an expression that should evaluate to byte, short, char or int primitive data types, only. In a switch block, there can be one or more labeled cases. The expression that creates labels for the case must be unique — the switch expression match with each case label. Only the matched case execute if no case matches then the default statement (if present) is executed. The switch statement gives you the chance to test for ranges of values for a variable and may be used instead of an IF…ELSE statement. The switch statement structured like this:

General Syntax of Switch Statement

switch(control_expression){
     case expression 1:<statement>;
     case expression 2:<statement>;
          ......
     case expression n:<statement>;
     default:<statement>;
}//end switch

We begin with ‘switch’ followed by parentheses. In between the parentheses, we place the variable that we want to check, and we follow this with the curly brackets.   The remainder of our switch statement placed in between those brackets. For  every value that checks, the word ‘case’ must be used before the value to check:  
case value:  
A colon follows the value, and then we state what should happen if a match found. It is the code that executes; we must use the break keyword for breaking out of the individual case in our statement.  
At the end we have a default value; this is optional, and you can use it if you have values that the variable may store but that have not to check for in any other part of the statement.
This is probably a little confusing at the moment, especially if you are completely  new to Java programming. Try the java program using switch case; first save and close the code you are working on now and open a new project. Then input the code:

Switch Case in java example programs

Java switch statement example: Here expression "day" in switch statement evaluates to 5 which matches with a case labeled "5" so code in case 5 is executed that results to output "Friday" on the screen.

int day = 5;
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("Thrusday");
      break;
      case 5:System.out.println("Friday");
      break;
      case 6:System.out.println("Saturday");
      break;
      case 7:System.out.println("Sunday");
      break;
      default:System.out.println("Invalid entry");
      break;
}

The switch statement checks the variable to see what is in it before working through each case statement in order. When a  match found, the statement stops and case code execute; the statement then broke out.

Repetition Statements

As I mentioned earlier, much of the programming is sequential, and that means  Java execute it from top to bottom unless it is told not to. Earlier we looked at the IF statement for telling Java if we don’t want something executed. There is another way to do it though. We interrupt the program flow by using loops.  
A loop forces your program to start again or to go back to a specific place,  allowing that piece of code to repeatedly executed. Let’s see how this works with an example. We’ll assume that we want to add the numbers 20 through 30 together; this is easy:  
int addition = 20 + 21 + 22 + 23 + 24 + 2 + 36 + 27 + 28 + 29 + 30;  
So, that work when you only have a few numbers to add up but what if you wanted to add a huge range, say all the numbers between 1 and 10,000. A loop can be used on one line of code over and over again until we reached 10,000, and then we break out of the loop and continue with the rest of the code. 

The For Loop

The For Loop  We’ll begin with the For Loop, the most commonly used Java loop. It is also a loop statement that provides a compact way to iterate over a range of values. Think of it as  ‘looping FOR a set number of times’. From a  user point of view, this is reliable because it executes the statements within this block repeatedly till the specified conditions is true.
The For Loop structured like this:  
for ( start_value; end_value; increment_number ) {  //YOUR_CODE_GOES_HERE  }
After ‘for’ (all in lowercase) we have the parentheses. In these, we must have three things – the start value of our loop, the end value and a method that takes you from the start to the end. It is the increment number, and it would usually start at  1; it can be anything, though, sections of 10 or, where you have a vast range to add, even 100. 

Following those parentheses, we have the curly brackets, again for sectioning off the code that is to execute repeatedly. Have a look at this example; it may make things clearer.  
Again, we need a new project for this so save the one you are working on and open  a new one. Your project name will be ‘loops’ and the class is ‘ForLoops’. Now add  this code:

publicclass ForLoops {
      publicstaticvoid main(String[] args){
             int loopVal;
             int end_value =21;
             for(loopVal =10; loopVal < end_value; loopVal++){
                    System.out.println("Loop Value = "+ loopVal);
             }
      }
}

We set a variable, an int called loopVal and, on the next line down; we set another one this hold the end value, set to 21. We want to loop around printing numbers from 10 to 20.   

Note what is inserted between the parentheses:  
loopVal =10; loopVal < end_value; loopVal++  
First, we tell Java which number to start from; in our case, we have assigned the loopVal variable with a value of 10, the first one in the loop. Second, we used some  of our conditional logic:  
loopVal < end_value  
What this says is that loopVal is less than the end_value; while the loopVal variable stays less than end_value, the for loop continue looping.  This goes for any for  loop – while it is TRUE that loopVal remains less than end_value, Java will carry on  looping the code inserted between the curly brackets.
The final part in our parentheses is: 

loopVal++   

It tells Java that we want it to start from the loopVal start value and go to the next sequential value. As we are counting 10 to 20, the next number 11.  However, rather than using that piece of code, we could have done this: 

loopVal = loopVal + 1 

To the right of our = sign, we have loopVal +1. It tells Java that a value of 1  should be added to the value already in loopVal. The result of the additional store in the loopVal variable to the left of the = sign. The result is that a value of 1 continuously added to that new value and this is called incrementing. It used so  much now that a new notation invented for it – a new variable that is called ++:  int some_number = 0; 

some_number++;  

When Java executes the code, a value of 1 assigned to some_number, the short  version of this:
int some_number = 0;  
some_number = some_number + 1;  
As a recap, this is what the for loop says:  
• 10 is the loop’s start value  
•  It continues looping while the value is less than 21  
•  To reach the end value, 1 must constantly  add to the start value 

Within the curly brackets for the for loop, we have:  
System.out.println("Loop Value = " + loopVal);  
The value in the loopVal variable is what gets printed, together with some text, so run this and see what happens.  
Your program is trapped in this loop and is being forced to continually go round,  each time adding a value of 1 to the loopVal variable. It carries on for as long as the loopVal value is less than what stored in the end_value variable. The code within the set of curly brackets continuously executed, and that is what loops are all about – t continuously execute the code within the curly brackets.  This next example adds the numbers 1 through 10; have a go at it: 

publicstatic void main(String[] args) {
    int loopVal;
    int end_value =11;
    int addition =0;
    for(loopVal =1; loopVal < end_value; loopVal++){
           addition = addition + loopVal;
    }
       System.out.println("Total = "+ addition);
}

Run the program, and you should get 55 as the output. Note that this is pretty much the same as the previous code; we have two variables called loopVal and end_value, and then we have a third variable named addition. It is an int that contains the value from the addition. 

In between the for loop parentheses, it is once again much the same – for as long as loopVal remains lower than end_value, the loop repeats, each time adding 1 to the new value. Note the use of loopVal to denote our loop.  
There is just one line of code inside our curly brackets:  
addition = addition + loopVal;  
What this does is adds all our numbers; if you are at all confused about how it  works, begin at the right of the = sign, where it says:  
addition + loopVal;  
First time around, the additional variable is assigned a value of 0 while loopVal has a  starting value of 1. Java adds 1 to this value, storing the resulting number in the additional variable to the left of the = sign. The value stored in the additional variable is deleted, and the new value added. On the second loop, the following code goes  in between our parentheses: 

addition (1) + loopVal (2);  
As is fairly obvious, add 1 to 2, and you get 3, so this is the value that replaces what is in the additional variable. On the third loop, we see these as the new values:  
addition (3) + loopVal (3);  
Java adds the numbers together and stores 6 as the new value in the additional variable. It continues until all the additions done and the loop ended; the result printed is 55.

while loop statements

Another loop commonly used is the While loop, and these are far easier to understand than For loops are. It is looping or repeating statement. It executes a block of code or statements till the given condition is true. The expression must be evaluated to a boolean value. It continues testing the condition and executes the block of code. When the expression results to false control come out of the loop.

They structured like this: 

while ( condition ) {  } 

We start with ‘while’, lowercase, and insert the condition we want to test for in between our parentheses. Again we have those curly brackets containing the code  that will be executed. Have a look at this example of a while loop that prints text; 

have a go at it:

int loopVal = 0;
while ( loopVal < 5) {
       System.out.println("Printing Some Text");
       loopVal++;
}

Between the parentheses is the condition we are testing; the code is to loop for as long as the loopVal variable stays below 5.  Inside our curly brackets, a text line printed. Next, the loopVal variable must increment; leave this step out, and you have an infinite loop because loopVal will not be able to move past its start value of 0. 

Although loopVal was used to get to the end condition, when you need a checking value and not a counting value, the while loop is better. An example would be that the loop could continue until a specific key on the keyboard pressed, some thing you commonly see in games. We could say that to exit the while loop, the X key would need to be pressed (exiting out of the game at the same time).

Do ... While loop statements

It is another looping statement that tests the given condition past so you can say that the Do…While loop statement is a post-test loop statement. First, the do block statements execute when the condition given in while statement check. So in this case, even the condition is false in the first attempt, do the block of code is executed at least once.

int loopVal = 0;

do {
       System.out.println("Printing Some Text");
       loopVal++;
} while ( loopVal < 5 );

Once again, Java carries on looping until the final condition met but, this time,  the While section of the statement is near to the bottom while the condition doesn’t change – continue to loop while the value of loopVal is less than 5. 

The most significant difference is that the curly bracketed code in do…while executed a minimum of one time whereas, as far as the while loop is concerned, that condition could have been met already. If this is the case, Java breaks out of the loop and won't bother even looking the bracketed code, let alone execute it.  We can test this by trying the while loop first; change your loopVal value to a 5 and run it. You should see that the text does NOT get printed. Now change the do part of the loop, putting 5 as the value of loopVal, run it, and the text print just once before Java gets out of the loop.

Branching Statements

Break statements: The break statement is a branching statement that contains two forms: labeled and unlabeled. The break statement is used for breaking the execution of a loop (while, do-while and for) . It also terminates the switch statements.
Syntax:
 
break;  // breaks the innermost loop or switch statement.

 break label; // breaks the outermost loop in a series of nested loops.
Continue statements: This is a branching statement that are used in the looping statements (while, do-while and for) to skip the  current iteration of the loop and  resume the next iteration .
Syntax:
 
continue;

Return statements: It is a special branching statement that  transfers the control to the caller of the method. This statement is used to return a value to the caller method and terminates execution of method. This has two forms: one that returns a value and the other that can not return. the returned value type must match the return type of  method.

Syntax:
  return;
  return values;

return; //This returns nothing. So this can be used when method is declared with void return type.
return expression; //It returns the value evaluated from the expression.





About Dinesh Thakur

Dinesh ThakurDinesh Thakur holds an B.SC (Computer Science), MCSE, MCDBA, CCNA, CCNP, A+, SCJP certifications. Dinesh authors the hugely popular blog. Where he writes how-to guides around Computer fundamental , computer software, Computer programming, and web apps. For any type of query or something that you think is missing, please feel free to Contact us.



Related Articles