if statement

Definition and Comparison Operators

The if statement allows for conditional execution of code. The syntax of the command is:

if (expression) action

Put the "action" inside braces ( { } ) so that if you add a statement later, you don't need to worry about remembering to put the braces in at that time. This approach is calleddefensive programming (sort of like defensive driving - you do a little extra to avoid possible problems later). Using the brackets, this would look like:

if (expression) { action }

If you prefer, you may format this with the opening bracket on its own line, such as:

if (expression) { action; }

Inside (expression) we can use the following comparison (aka relational) operators in the expressions we create:

For instance, if we wanted to check if the value stored in a variable x is less than 3 we could write

if (x < 3) { // actions for when x<3 is true }

We can also separate conditional execution into two "either-or" conditions by using if-else. The syntax is (braces have been omitted for brevity):

if (expression) action1 else action2

For example, if we were handling menu choice values, this could be:

if (menuChoice == 3) { System.exit( 0); } else { System.out.println("menuChoice wasn't 3. "); }

We can also test for multiple conditions using if-else-if as follows (braces have been omitted for brevity):

if (expression1) action1; else if (expression2) action2; else if (expression3) action3; else defaultAction;

Note that since we are using this structure to represent choice between options all at the same level (e.g. "choose one of the following 3 menu options:."), we indent them all the same. If the checks for expressions2 and 3 were logically inside the first else, we would indent as follows:

if (expression1) action1; else if (expression2) action2; else if (expression3) action3;

In this way we use indentation to represent the logical organization of our code.

Common Problems

Problem confusing assignment '=' with equality comparison "=="

The first common error is to confuse the assignment statement ('=') with the equality operator ("=="). For example,

1 2 3 4 5 6 7

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

At first glance it seems that the println on line 6 will be executed, but actually the println on line 3 is executed. This is because inside the "if" on line 2 we mistakenly used a single equals symbol ("x = true") which does assignment, instead of the double equals sign which does comparison ("x == true"). Note that besides the actual assignment being done, the assignment statement taken as a whole is evaluated to be the value of the assignment. Thus the statement "if (x = true) " works the same as "if (true)" from the point of view of the if. (In other contexts, remember that non-zero values are considered true.)

Problem deciding which if an else belongs to

Let's say we have the following code:

1 2 3 4 5 6 7

int num = keyboard.nextInt(); if (num>=3) if (num==3) System.out.print("Is three."); else System.out.print("Less than three. "); System.out.println("Done.");

Does the else belong with the if on line 2, or the if on line3? Running this program gives the following results:

So we see that an else belongs with the closest previous open if, in this case the one on line 3. The indentation is misleading, but remember that the indentation is for us as humans and does not affect the logic of the program at all. If you wanted the else to correspond with the if on line 2, you would need to put braces around lines 3 & 4, giving code as follows:

1 2 3 4 5 6 7 8

int num = keyboard.nextInt(); if (num>=3) { if (num==3) System.out.print("Is three."); } else System.out.print("Less than three. "); System.out.println("Done.");

Note the brace at the end of line 2 and the new line 5 with a brace.

Boolean Operators and Short Circuit Evaluation

Inside an expression we can also use the following boolean operators:

&&

||

And

Or

For instance, if we wanted to check if the value stored in a variable x is greater or equal to 3 and not equal to 5 we could write

if ( (x >= 3) && (x != 5)) { // actions for when x is greater than or equal to 3 but not equal to 5 is true }

When there are several pieces in a logical expression inside an if statement (such as in the above example), Java uses what is called short-circuit evaluation. It only evaluates as much as it needs to decide whether or not a statement is true or false. For instance, in the statement if (a || b) { .... } we know that if either a or b is true, we will enter the if statement. (n.b. The || symbol means logical OR.) If only a is true, there is no need to evaluate b, since we will enter the if statement when b is true as well as when b is false. Consider the following example taken from the Savitch Java textbook to illustrate this:

if ( (kids != 0) && ((numberOfCookies/kids) >= 2) { System.out.println("Please, only take two cookies each."); }

The second part of the if condition is not executed, illustrating short-circuit evaluation. If you want to have complete evaluation, rather than && and ||, you can use a single & or a single |.

[CS Dept] [UIC] [Prof. Reed]