<< Hide Menu

📚

 > 

💻 

 > 

🖥

3.2 If Statements and Control Flow

2 min readjune 18, 2024

Avanish Gupta

Avanish Gupta

Milo Chang

Milo Chang

Avanish Gupta

Avanish Gupta

Milo Chang

Milo Chang

Introduction to Conditional Statements

Sometimes, we want our code to perform an action only if a certain condition is met (e.g., the integer is even), while other conditions will result in different actions. This requires us to use a conditional statement. These usually consist of a conditional statement header with the condition in it and a body that includes the code that is run if the conditional statement header is true.

If Statements

The simplest conditional statement is the if statement, also called a one-way selection. The if statement occurs if a block of code is only run if the condition is true. Here is the anatomy of an if statement:

some code before the if statement if (condition) { do this only if condition is true } do this after regardless of whether the condition was true or not

For the if condition, the convention is to keep the condition in parentheses in order to group the condition together and provide clarity. It is also a convention to keep the body of the if statement between brackets and indent the code in the body to show what statements are run. The brackets are essential. If the body has multiple lines but brackets are not placed around all of the lines, the computer will assume that the body consists only of the first line.

Example: Even Number Checker

Here, we are going to write a method to halve a number if it is even, but leave it unchanged if it is not.

public static int numberHalver(int number) { if (number % 2 == 0) { number /= 2; } return number; }

We can also write a method to check if a number is even as well, which will lead to an important fact about return statements.

public static boolean isEven(int number) { if (number % 2 == 0) { return true; } return false; }

Remember we said that the code following the conditional statement is run no matter what the condition evaluates to in the anatomy of an if statement? This is the one exception to that. If there is a return statement inside the conditional body, the method ends with that return value and never gets to the last part of the program. This is why we can put return false; after the conditional statement. False will only be returned if the conditional wasn't true (i.e., the number wasn't even) so the code inside the conditional body was not run (i.e., true was not returned).