1. The if-else
statement
Programs wouldn't be very useful if they always did the same thing, regardless of how external circumstances change. A program needs to be able to adapt to different situations and take certain actions in some situations, and to act differently in others.
In Java, this is done with a conditional statement, which uses a special keyword that lets you execute different blocks of commands depending on the truth value of a condition.
A conditional statement consists of three parts: condition, statement 1 and statement 2. If the condition is true, then statement 1 is executed. Otherwise statement 2 is executed. Both commands are never executed. Here's the general appearance of this kind of statement:
if (condition)
statement 1;
else
statement 2;
It is quite understandable when written in plain English like this:
If condition is true, then
execute statement 1;
otherwise
execute statement 2;
Examples:
Code | Explanation |
---|---|
|
The screen output will be:
|
|
The screen output will be:
|
|
The screen output will be:
|
2. Block of statements
If the condition is satisfied (or not) and you want your program to execute several commands, you can combine them into a block.
To combine commands into a block, you "wrap" them in curly braces. Here's how it looks in general:
{
statement 1;
statement 2;
statement 3;
}
You can have as many statements as you want in a block. Or even none.
Examples of an if-else statement combined with a block of statements:
Code | Explanation |
---|---|
|
The screen output will be:
|
|
The screen output will be:
|
|
The empty block will be executed. The code will run fine, but nothing will be displayed. |
3. Abbreviated form of the if
statement
Sometimes it you need to execute one or statements if the condition is true but nothing should be done if it is false.
For example, we can specify this command: If Bus No. 62 has arrived, then get aboard
, but don't react if the bus isn't here. In Java, this scenario lets us use an abbreviated form: an if
statement without an else
block.
In other words, if statements(s) needs to be executed only if the condition is true and there are no commands to be executed when the condition is false, then you should use the if
statement, which is concise and omits the else
block. It looks like this:
if (condition)
statement 1;
Below are three examples of equivalent code:
Code | Explanation |
---|---|
|
The screen output will be:
|
The program has an else
block, but it is empty (there are no statements between the curly braces). You can simply remove it. Nothing will change in the program.
Code | Explanation |
---|---|
|
The screen output will be:
|
|
The screen output will be:
|
GO TO FULL VERSION
🤓🤓