Skip Top Navigation Bar

Using If Statements

As we saw in our algorithms section, we will want our programs to do different things based on conditions. One way to have a program behave differently under different conditions is to use if statements.

If Statements

An if statement allows you to perform certain functions when a Boolean expression is true and other functions (or nothing at all) when a Boolean expression is false.

The structure of an if statement is as follows:

if (<boolean expression>) {
    //statements to execute if the boolean expression is true
}

With an if statement, the statements in the body of the if statement, the ones enclosed in braces ({ }), are only executed in the boolean expression evaluates to true. If the boolean expression evaluates to false, these statements are skipped. Either way, the program continues with the next statement after the closing brace.

Tracing if Statements


Your Turn

Let's try it in the Java Playground.

if..else Statements

Often we have a set of statements we want to execute when the boolean expression evaluates to true and a different set of statements when the boolean expression evaluates to false.

Tracing if..else Statements


Your Turn

Let's try it in the Java Playground.

Formatting If Statements

The way code is formatted is mostly for those that are reading the code. If you are working with other programmers on a project or if you need to add to an existing project, the format of the code can help make the code more readable. Often, style guides exist to help make program code more uniform. A few style things to note:

Resources

Next Learn Tutorial

-Learn: Using Nested if Statements