A Quick Review of if-then-else Statements in Java

There is a common misunderstanding in the parts that make up an if-then-else statement. Many students only recall two of the parts: if and else. However, remember that there are three parts that make up this conditional statement: if, else if, and else.

Lets take a simple example: you want create a program that will decide what a student’s letter grade (i.e. A, B, C, D, F) will be based on a numerical value (i.e. 87, 45, 72, etc.).

ifthenelse_01

In this if-then-else statement, Java will first check to see if examScore is 90 or greater, if it is then the grade will be an A.
If not, then it will go into the first else if statement and check to see if the examScore is 80 or greater, if yes then the grade is a B.
If not, then it will go into the second else if statement and check to see if the examScore is 70 or greater, and if it is then the grade is a C.
This will keep happening until it comes to the else statement; if Java ever gets to this point, then it knows that the else if statements that came before it have failed (or in technical terms, whose conditionals have resulted in a false), in which case the grade will automatically be an F.

In this above case, The grade is B will be printed out because the first if statement returned a false, whereas the first else if statement returned a true, thus setting grade equal to B.

If you are ever in a situation where you have to evaluate multiple things (as is the case above), then you will want to use the if/else if/ else structure. Many students will try to do something like the following, which is incorrect:

ifthenelse_02

 

In this case, The grade is D will be printed out because Java executed all of the if statements. The flow of logic looks something like this:

Check to see if examScore is >= 90 –> it is not, there is no else if or else statement after this if statement, so don’t do anything

Onto the next line of code, there is an if statement, so check to see if examScore is >= 80 –> this is true, so set grade = B

Next line of code, another if statement, check to see if examScore is >= 70 –> yes it is true, so set grade = C

Next line of code, an if statement, check to see if examScore is >= 60 –> it is true, so set grade = D

Next line of code, we have an else statement, but the previous if statement already got executed because it was true, so do not execute this else statement.

 

In this second example, by having multiple if statements Java checks every one of single one of them regardless of whether the previous if was true or not. This is not what you want! You want to use the if/ else if/ else structure because the else if statements will only execute if the previous if or else if statements returned a false.

 

If you have any comments or questions, please do not hesitate to write below. In order to comment, you just need your Bentley shortname and password.