Last Updated: 15 January, 2023
The objective of this tutorial is to give you a basic understanding of control flow statements using Java if and if...else statements with examples.
If-else statements are conditional statements that help us run a specific block of code if the condition is either true or else.
The if statement is true, it will execute a block of code; otherwise, it will not. But what if we want to do something else if the condition is false, here comes the else statement. We can use the else statement with the if statement to execute a block of code when the condition is false.
The else statement is optional; it comes with the if statement only. It cannot be written without an if statement.
Before we proceed, let's take a look at the syntax of an if-else statement:
It has a single block. The if statement is true, then execute the block; otherwise, skip the block and execute the next instruction.
Example:
Output
Your car speed is greater than 30 KM/H
It has two blocks. The first is an if statement block, followed by an else statement block. The if statement is true, then execute the if block; otherwise, the else block will be executed.
Example:
Output
Your card speed is more than specified speed
It has multiple blocks. The if-else-if ladder is used to choose between multiple options. The if statements are executed from the top down. If any if statement matches the given condition, then it executes the associated block, and the rest of the ladder is bypassed. If none of the conditions is true, then the final else statement will be executed.
Example:
Output
Speed is too fast
The nested if statement represents the if block inside another if block. The first if statement is called Outer if and the inside declared if statement is called inner if. The inner if only executes if the outer if condition is true.
Example:
Output
Speed and DL are OK.
That's all guys, hope this Java article is helpful for you.
Happy Learning... 😀
feedback@javabytechie.com