🌟 Join our Telegram group for exclusive updates! Join Now Get Involved

if…else Statement

Java If-Else Statement Example

The if...else statement in Java provides a way to execute different blocks of code based on the evaluation of a boolean expression. If the boolean expression in the if statement is true, the code inside the if block is executed. If the expression is false, the code inside the else block is executed.

Example:

public class IfElseStatementExample {
    public static void main(String[] args) {
        int x = 10;

        // If-else statement
        if (x > 5) {
            System.out.println("x is greater than 5");
        } else {
            System.out.println("x is 5 or less");
        }

        // Another example
        int y = 7;
        if (y % 2 == 0) {
            System.out.println("y is an even number");
        } else {
            System.out.println("y is an odd number");
        }
    }
}

In this example:

  • The first if...else statement checks if x is greater than 5 and prints a message accordingly.
  • The second if...else statement checks if y is an even or odd number based on the remainder when divided by 2.

You can have multiple else if blocks to check additional conditions. The if...else statement allows you to handle scenarios where there are two possible outcomes based on the evaluation of a condition. The code inside the else block is executed only if the condition in the if statement is false.

Cookies Consent

This website uses cookies to ensure you get the best experience on our website.

Cookies Policy

We employ the use of cookies. By accessing BYTEFOXD9, you agreed to use cookies in agreement with the BYTEFOXD9's Privacy Policy.

Most interactive websites use cookies to let us retrieve the user’s details for each visit. Cookies are used by our website to enable the functionality of certain areas to make it easier for people visiting our website. Some of our affiliate/advertising partners may also use cookies.