Making a decision with IF-Else
- Eclipse: Oxygen
- Java: 1.8
In this tutorial, we deal with the advanced details of the if-else condition.
IF Statement
If statement is one of the control flow statement. In Java If statement is used make decision based on condition.
In If statement we test a condition, if the condition is true, the code inside “If block” will be executed and if the condition is false, the code inside if the condition is ignored. Braces “{ }” decides the scope of if statement.
Syntax for If statement:
1 2 3 4 |
if(condition) { statement1... statement2... } |
In the following example, if the value of int x equals to 5 then statement inside “If block” will be executed.
1 2 3 4 5 |
public static void main(String[] args) { int x = 5; if (x == 5) { System.out.println("Value of x is 5"); } |
Output
Value of x is 5
If the condition is false then statement inside if block is will be ignored and code outside the scope of “If block” will be executed.
1 2 3 4 5 6 7 |
public static void main(String[] args) { int x = 6; if (x == 5) { System.out.println("Value of x is 5"); } System.out.println("What Happened"); } |
Output
What Happened
IF-Else Statement
An if statement can be followed by an optional else statement, which executes when the Boolean expression is false.
“If” block would be executed when the condition is true (if x is equal to 5), otherwise “else” block is executed when the condition is false (value of x is greater than 5. Which will execute the ‘else’ block).
1 2 3 4 5 6 7 |
public static void main(String[] args) { int x = 6; if (x == 5) { System.out.println("Value of x is 5"); }else { System.out.println("Value of x is not 5"); } |
Output
Value of x is not 5
Contributed by: Poonam Tomar