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

if Statement

Java If Statement Example

The if statement in Java is a conditional statement that allows you to execute a block of code based on the evaluation of a boolean expression. If the boolean expression is true, the block of code inside the if statement is executed; otherwise, it is skipped.

Example:

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

        // Simple if statement
        if (x > 5) {
            System.out.println("x is greater than 5");
        }

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

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

In this example:

  • The first if statement checks if x is greater than 5 and prints a message if true.
  • The second if-else statement checks if x is greater than 20 and prints a message accordingly.
  • The third if-else if-else statement checks multiple conditions and prints messages based on the evaluation of these conditions.

You can have multiple else if blocks to check additional conditions. The if statement allows you to control the flow of your program based on different conditions. Keep in mind that only the block of code associated with the first true condition (or the first if or else if block with a true condition) will be executed.

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.