Configuration

Night mode

Java Selection Statements

Java Selection Statements Course

Engineers From These Top Companies and Universities Trust EXLskills

1M+ Professionals | 100+ Institutions

This is the EXLskills free and open-source Java Selection Statements Micro Course. It guides learners via explanation, demonstration, and thorough practice, from no more than a basic understanding of Java, to a moderate level of understanding regarding Java selection statements.

Is this course FREE?

Yes, this a 100% free course that you can contribute to on GitHub here!

Have more questions?

Basics

The if else Statements

Let's start exploring the structure of an if statement in Java by relating it to a real life scenario. Suppose you are walking down the street with an umbrella. We ask one question in order to get a true or false response: "is it raining?". If we answer yes, or "true", then one course of action takes places, we open and use the umbrella. If the answer is no, or "false", another course of action takes place, the umbrella stays closed. This is the basis for an if statement in Java; one of two different courses of action take place based on a "true" or "false" answer. These types of statements involve a binary (two-way) decision. Play with the example below, which uses our umbrella scenario, by changing the boolean "rain" to "false".

The if statement above tests to see if the boolean value of "rain" is true. If it is, the "true branch" statement is executed. If not, the "false branch" statement is executed. Notice how we separate the "true branch" and the "false branch" by the reserved word else. The expression that goes inside the if statement must evaluate to true or false for the statement to execute, and anything that evaluates to a boolean value can be placed inside brackets.

"If you're tired, go to sleep. Otherwise, stay awake."

"If you're hungry, eat. Otherwise, don't eat."

The if statement allows the programmer to structure results using the same logic we use in our everyday lives.