Software Development Basics – Control Statements

Life is simple. You go on living in what looks like a straight line, without making decisions and without repeating any activity. It seems the perfect world…. until you realize it isn’t!

 

As in real life, writing code involves making decisions. Depending on some values, or the answer to some question or calculation or even the user input, the code will do something different. This is when it has to make decisions…. and to make decisions you use control (or conditional) statements.

 

There will be times when you need to repeat the same task many times, and you won’t know exactly the total number of times you need to repeat them. Instead of writing the same code over and over again, you can use control statements to repeat the same instructions until the processing is done.

 

An example of this will be reading data from a database. You can get one row of data, or two, or ten. You don’t know. But to process them you will do exactly the same to every row. So you just write the code once and repeat until you read all the rows.

 

Another option is that after some condition is met, you want to stop cycling through the same instructions and continue the execution of your code. This also can be done in Java.

 

With control statements your code won’t run from top to bottom. It will execute some code depending on a condition, or will repeat some lines of code for a given number of times.

 

Control statements can be divided in three categories:

  1. Decision-making statements
  2. Looping statements
  3. Branching statements

 

Decision-making statements

 

if and if-else statements

 

Perhaps the most common used of all the control statements. It allows you to evaluate a condition and do something if the condition evaluates to true. If your condition is false, then the code won’t execute.

 


/*

* If statement. The code within the if will only be executed

* if the value of gradeOfLastExam is greater than 5.

*/

int gradeOfLastExam = 10;

if(gradeOfLastExam > 5){

    System.out.println("Congratulations. You passed the exam.");

}

/*

* Here you see that the condition is false, so the code within

* the if is not executed.

*/

if(gradeOfLastExam <= 5){

    System.out.println("You failed the exam.");

}

 
You can execute any number of lines of code within the if. Be sure to add the curly brackets to indicate which lines will be within the if statement. (If you only have one line of code, you are allowed to write your line of code and omit the curly brackets).

 

There is a variant of the if statement. You can use the if-else statement if you want to evaluate a condition and if it is true, do something and if it is false do something else. This can apply to our previous example like this:

 


/*

* There is a better way to do this. You can use the if-else statement

* to do something if the condition is true or do something else if

* the condition is false. All in the same if block.

* Notice how you can omit the curly brackets since there is only

* one line of code for the if and the else.

*/

if(gradeOfLastExam > 5)

    System.out.println("Congratulations. You passed the exam.");

else

    System.out.println("You failed the exam.");

 

What if you want to evaluate many conditions? You can use multiple if-else if statements.

 


/*

* For multiple evaluations, you can use if-else if statements.

* You can use else too at the end if you want to do something

* if the condition is not true in all the if-else if evaluations.

*/

gradeOfLastExam = 8;

if(gradeOfLastExam >= 9){

    System.out.println("You don't need to take the final exam!");

}else if(gradeOfLastExam >=6){

    System.out.println("You need to study for the final exam.");

}else if(gradeOfLastExam >= 0 && gradeOfLastExam < 6){

    System.out.println("You need to take the course again.");

}else{

    System.out.println("You probably live in a parallel universe with negative grades.");

}

 

 

Switch statement

 

The switch statement can do different things depending on the value of a variable that it evaluates. In this example, you have a variable called countryCode that is set to a specific country code value. The switch evaluates different cases to see if it fits one of them. If the countryCode variable has a specific value that is included in the switch, for example “mx”, then it will execute the code that is within that case.

 

It is very important that you add the break keyword at the end of each case, if not the switch will execute ALL the instructions that it finds until it gets to a break, even though they are in a different case.

 

There is a special case, called the default case. If the value of your variable doesn’t match any of the ones available in the case, then the code in the default case is executed.

 

The switch-case doesn’t work for all data types. It only works for byte, short, char, int, Enums (you will find out what Enums are later) and Strings.

 


/*

* countryCode has a value that represents a country. This switch statement

* tries to determine which country it is. In each case, you can add a different

* String value so then the countryName variable can be set correctly. If the countryCode

* value is not here, it will execute the default statement.

* IMPORTANT: add the break keyword at the end of teach case.

* EXCEPTION: if you want to adjacent cases to do the same, omit the break keyword and have something like this:

*

* case 1:

* case 2:

* case 3:

* // do something here.

* break;

* default:

*  // do something else here.

*  break;

*

* Here if your switch value has value of 1, 2 or 3, it will do the same for all of them.

*/

String countryCode = "mx", countryName = "";

switch(countryCode){

case "us":

    countryName = "United States";

    break;

case "mx":

    countryName = "Mexico";

    break;

case "arg":

    countryName = "Argentina";

    break;

case "ca":

    countryName = "Canada";

    break;

case "fr":

    countryName = "France";

    break;

default:

    countryName = "I don't know";

    break;

}

System.out.println(countryName);

 

Looping statements

 

while

 

The while loop statement execute a set of instructions over and over again while the condition it has is true. You need to be sure to change the condition within the while loop so it changes to false at one moment. If you don’t do this, your program will get locked forever.

 

In its general form the while statement looks like this

 


while(condition){

// instructions to execute.

}

 

The first thing the while loop does is to evaluate the condition. Then if it is true, it goes and execute all the instructions within the while. Once it finishes, it goes again to the start and evaluates the condition and repeat. The last time it evaluates the condition and it is false, and it does not execute the instructions anymore.

 


/*

* While statement will execute all the instructions within the while

* until the condition changes to false.

*

*/

int count = 10;

while(count >= 0){

    System.out.println("I am in a while statement");

    System.out.println("My count is " + count--);

}

 

do-while

 

This is a variant of the while statement. It goes like this

 


do{

    // whatever you want to do

}while(condition);

 

The difference is that it evaluates the condition AFTER all the instructions are executed. So this do-while statement will execute the instructions at least once, if the condition is false the first time. Be careful when using the do-while statement.

 


/*

* Do-while statement will execute the instructions first and then

* it will evaluate the condition. If it is false it will exit the loop,

* having at least executed the instructions once.

*/

boolean conditionToBeFalse = false;

do{

    System.out.println("I will show in the console even though the condition is false!");

}while(conditionToBeFalse);

System.out.println("Condition is false so I'm out of the loop");

[/code[

&nbsp;
<h3>for</h3>

This is the last, and perhaps the most used, loop statement. It allows you to go over - iterate - a range of values. In its general form it looks like this:



for(initalization; condition; change){
// your code here please
}

 

The for statement has an internal counter that needs to be initialized. That is the initialization. This counter will be evaluated after each loop - or iteration. That is the condition. When the condition is false it will exit the loop, and while the condition is true it will repeat all the instructions within the for. After each iteration, the counter will change, normally increment or decrement its value. That is the change.

 


/*

* This code will print the values from 1 to 10 within the for statement.

* Notice how the initialization of variable i is done.

* The condition is that while i <= 10 repeat the loop.

* And the change is the increment by 1 of the variable i after each loop.

*/

for(int i = 1; i <= 10; i++){

    System.out.println("Count i: " + i);

}

System.out.println("Condition is false so I'm out of the loop. Also i variable does not exist anymore");

 

You need to know that the initialization, condition, and change within the for are optional. If you don’t add any of these, you get an infinite loop. Sometimes this is useful.

 


for( ; ; ){
// Instructions.
}

 

There is a special type of for. When you have a collection of objects or values (more on this in later posts) normally you need to iterate through all the members of this collection. This special form of the for statement lets you do this easily.

 

This form looks like this in its general form:

 


for(Type variableName : collection){

}

 

For example, if you have an array of int (an array is a collection of values or objects of the same type, in this case int values. More on arrays later.) Type will be int and variableName will be one of the values on the array. The first iteration it will have the first value, the second iteration the second value and so on.

 


/*

* If you have a collection of objects or values (we will cover this in a later post)

* you can use this type of for statement. It will iterate over each element of the

* collection.

*/

int[] arrayOfNumbers = {5, 10, 15, 20, 25, 30, 35 };

for(int number : arrayOfNumbers){

    System.out.println("Current number in arrayOfNumbers: " + number);

}

System.out.println("I'm done iterating over all the arrayOfNumbers. No more numbers left to process. I'm out of the for.");

 

 

Branching Statements

 

Sometimes you will need to get out of your loop before it ends, maybe when some condition is met. Or maybe you need to “jump” a specific iteration. When these situations appear, you make use of the branching statements.

 

There are three branching statements: break, continue and return.

 

break

 

We used this before in the switch statement. What it does is to go out of the case statement. You can use it also in the while, do-while and for statements and what it will do is to get out of the loop whenever you use it, even though the loop is not finished yet.

 


/*

* This for is programmed to go from 0 to 9. But when the condition is met

* i == 5, it uses the break statement causing the for loop to terminate.

* It also works for while and do-while loops.

*/

for(int i = 0; i < 10; i++){

    if(i == 5){

        System.out.println("A condition is met and break is called. I'm going out!");

        break;

    }

    System.out.println("I am in the for loop.");

}

System.out.println("I am out of the loop although it didn't complete all the iterations");

 

continue

 

Continue statement is used when you don’t want to execute some instructions in a specific iteration of a loop. It works for the for, while and do-while loops.

 


/*

* This for is programmed to go from 0 to 9. But when the condition is met

* i == 5, it uses the continue statement causing the loop to go to the next

* iteration.

*

*/

for(int i = 0; i < 10; i++){

    if(i == 5){

        continue;

    }

System.out.println("i value: " + i);

}

System.out.println("I am out of the loop. I missed the 5 i value!");

 

return

 

The return statement will terminate the current method you are using and will return to where the method was called. More on methods on later posts.

 

You will see if you execute this code that the last println is not called, because return is used within the loop and it terminates the loop and the main method where the for loop is executed.

 


/*

* This for is programmed to go from 0 to 9. But when the condition is met

* i == 5, it uses the return statement causing the loop and the main method

* to terminate.

*

*/

for(int i = 0; i < 10; i++){

    if(i == 5){

        return;

    }

System.out.println("i value: " + i);

}

System.out.println("I am out of the loop. I am not printed!");

 

You can find all the code in this Github link.

----

 

OK this is all for today. This was a lot of information but this will be really useful to you later on your programming career. I try to make the examples as simple as possible so you understand the basics and the functionality of each topic. After a couple of posts, I think, you will have enough knowledge to understand a more complex example, more real-world like.

 

See you next week

 

** Questions? Leave a comment or email me.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s