Getting to know if-else statements in java programming

In this blog, I will show some sample codes about If-Else Statements in Java. The If-Else Statements is used to test the condition of the given statement. Whether the output is True or False. We can also test multiple condition. I will demonstrate some basic but straight forward in applying the If-Else Statement.

Java supports logical condition from mathematics:

  • Less than : a < b
  • Less than or equal to: a <= b
  • Greater than: a > b
  • Greater than or equal to: a >= b
  • Equal to a == b
  • Not Equal to: a != b.

Java has the following conditional statements:

  • If Statement
    – This statement is used to specify the code if the condition is true.

    Syntax:

if (condition) {
// block of code to be executed if the condition is true
}


Sample Code:

Output:

  • Else Statement
    – This statement is used to specify the code if the condition is false.

Syntax:

if (condition) {
// block of code to be executed if the condition is true
} else {
// block of code to be executed if the condition is false
}

Sample Code:

Output:

The statement is True:

The statement is False:

  • Else-IF statement
    – This statement is used to specify a new condition if the first condition is false.

    Syntax:

if (condition1) {
// block of code to be executed if condition1 is true
} else if (condition2) {
// block of code to be executed if the condition1 is false and condition2 is true
} else {
// block of code to be executed if the condition1 is false and condition2 is false
}

Sample Code:

Output:
-If the condition 1 is True.

-If condition1 is false and condition2 is true.

-If condition1 is false and condition2 is false.

Leave a Comment

Your email address will not be published. Required fields are marked *