A lecture snippet with a mentor as part of the Codegym University course. Sign up for the full course.
"Hi, Amigo. Today we'll talk about if/else statements."
"Programs would be of little use if they didn't respond to changing external circumstances. A program needs to know how to adapt to circumstances and perform one action in one case and other actions in other cases. In Java, this is achieved using the 'if/else statement' – a special construct that makes it possible to perform different code blocks if a condition is satisfied."
"It consists of three parts: 'condition', 'command 1' and 'command 2'. If the condition is true, then 'command 1' is executed, otherwise 'command 2' is executed. These commands are never both executed. The statement looks more or less like this:"
if (condition)
command_1;
else
command_2;
"How exciting! I think that statement will make programming much more interesting!"
"Yep. Here are a couple of examples for you:"
Code | Explanation | |
---|---|---|
1 |
|
If a is less than b, the first command will be executed. Otherwise the second command will be executed. The commands are never both executed. |
2 |
|
You can replace one command with a code block. The rest is the same. |
3 |
|
You can omit the else block if it's empty. These three examples are entirely equivalent. You can omit the curly brackets if you only need to execute one command. If you have more than one command, you need to keep the brackets. |
4 |
|
|
5 |
|
"Diego just asked me to give you a few tasks."
A lecture snippet with a mentor as part of the Codegym University course. Sign up for the full course.
GO TO FULL VERSION