Skip to content
On this page

If Statement

In a Java program, if you want to decide whether to execute a certain piece of code based on conditions, you need an if statement.

The basic syntax of the if statement is:

java
if (condition) {
  // Execute when conditions are met
}

Based on the calculation result of if ( true or false ), the JVM decides whether to execute the if statement block (that is, all statements contained in curly braces {}).

Let's look at an example:

java
public class Main {
    public static void main(String[] args) {
        int n = 70;
        if (n >= 60) {
            System.out.println("Passed");
        }
        System.out.println("END");
    }
}

When the condition n >= 60 evaluates to true , the if statement block is executed and "Passed" will be printed. Otherwise, the if statement block will be skipped. Modify the value of n to see the execution effect.

Note that the block contained in the if statement can contain multiple statements:

java
public class Main {
    public static void main(String[] args) {
        int n = 70;
        if (n >= 60) {
            System.out.println("Passed");
            System.out.println("Congratulations");
        }
        System.out.println("END");
    }
}

When the if statement block has only one line of statements, the curly braces {} can be omitted:

java
public class Main {
    public static void main(String[] args) {
        int n = 70;
        if (n >= 60)
            System.out.println("Passed");
        System.out.println("END");
    }
}

However, omitting the curly braces is not always a good idea. Suppose that at some point, you suddenly want to add a statement to the if statement block:

java
public class Main {
    public static void main(String[] args) {
        int n = 50;
        if (n >= 60)
            System.out.println("Passed");
            System.out.println("Congratulations"); // Note that this statement is not part of the if statement block
        System.out.println("END");
    }
}

Due to the indentation format, it is easy to regard both lines of statements as the execution block of the if statement, but in fact only the first line of statements is the execution block of if statement.

It is more likely to cause problems when using version control systems such as git to automatically merge, so it is not recommended to ignore the curly braces.

Else

The if statement can also write an else { ... } . When the condition is judged to be false , the else statement block will be executed:

java
public class Main {
    public static void main(String[] args) {
        int n = 70;
        if (n >= 60) {
            System.out.println("Passed");
        } else {
            System.out.println("Failed the course");
        }
        System.out.println("END");
    }
}

Modify the value of n in the above code and observe the statement block executed by the program when the if condition is true or false .

Note that else is not required.

You can also use multiple if ... else if ... in series. For example:

java
public class Main {
    public static void main(String[] args) {
        int n = 70;
        if (n >= 90) {
            System.out.println("excellent");
        } else if (n >= 60) {
            System.out.println("Passed");
        } else {
            System.out.println("Failed the course");
        }
        System.out.println("END");
    }
}

The effect of series connection is actually equivalent to:

java
if (n >= 90) {
    // n >= 90 is true:
    System.out.println("excellent");
} else {
    // n >= 90 is false:
    if (n >= 60) {
        // n >= 60 is true:
        System.out.println("Passed");
    } else {
        // n >= 60 is false:
        System.out.println("Failed the course");
    }
}

When using multiple if in series, pay special attention to the order of judgment. Observe the following code:

java
public class Main {
    public static void main(String[] args) {
        int n = 100;
        if (n >= 60) {
            System.out.println("Passed");
        } else if (n >= 90) {
            System.out.println("excellent");
        } else {
            System.out.println("Failed the course");
        }
    }
}

The execution found that when n = 100 , the condition n >= 90 is met, but the output is not "excellent" but "Passed" . The reason is that when the if statement is executed from top to bottom, n >= 60 is first judged to be successful. After that, the subsequent else will no longer be executed, so if (n >= 90) has no chance to execute.

The correct way is to judge according to the judgment range from large to small:

java
if (n >= 90) {
    // ...
} else if (n >= 60) {
    // ...
} else {
    // ...
}

Or rewrite it as judging from small to large:

java
if (n < 60) {
    // ...
} else if (n < 90) {
    // ...
} else {
    // ...
}

When using if , pay special attention to boundary conditions. For example:

java
public class Main {
    public static void main(String[] args) {
        int n = 90;
        if (n > 90) {
            System.out.println("excellent");
        } else if (n >= 60) {
            System.out.println("Passed");
        } else {
            System.out.println("Failed the course");
        }
    }
}

Suppose we expect a score of 90 or higher to be "excellent", but the above code outputs "pass" because the effects of > and >= are different.

As mentioned before, floating point numbers often cannot be accurately represented in computers, and calculation errors may occur. Therefore, it is unreliable to use == to judge the equality of floating point numbers:

java
public class Main {
    public static void main(String[] args) {
        double x = 1 - 9.0 / 10;
        if (x == 0.1) {
            System.out.println("x is 0.1");
        } else {
            System.out.println("x is NOT 0.1");
        }
    }
}

The correct method is to judge by using the difference value to be less than a certain critical value:

java
public class Main {
    public static void main(String[] args) {
        double x = 1 - 9.0 / 10;
        if (Math.abs(x - 0.1) < 0.00001) {
            System.out.println("x is 0.1");
        } else {
            System.out.println("x is NOT 0.1");
        }
    }
}

Determine Reference Type Equality

In Java, to determine whether value type variables are equal, you can use the == operator. However, to determine whether reference type variables are equal, == means "whether the references are equal", or whether they point to the same object. For example, the following two String types have the same content, but they point to different objects respectively. If == is used to judge, the result is false :

java
public class Main {
    public static void main(String[] args) {
        String s1 = "hello";
        String s2 = "HELLO".toLowerCase();
        System.out.println(s1);
        System.out.println(s2);
        if (s1 == s2) {
            System.out.println("s1 == s2");
        } else {
            System.out.println("s1 != s2");
        }
    }
}

To determine whether the contents of variables of reference types are equal, equals() method must be used:

java
public class Main {
    public static void main(String[] args) {
        String s1 = "hello";
        String s2 = "HELLO".toLowerCase();
        System.out.println(s1);
        System.out.println(s2);
        if (s1.equals(s2)) {
            System.out.println("s1 equals s2");
        } else {
            System.out.println("s1 not equals s2");
        }
    }
}

Note: When executing the statement s1.equals(s2) , if the variable s1 is null , NullPointerException will be reported:

java
public class Main {
    public static void main(String[] args) {
        String s1 = null;
        if (s1.equals("hello")) {
            System.out.println("hello");
        }
    }
}

To avoid NullPointerException errors, you can take advantage of the short-circuiting operator && :

java
public class Main {
    public static void main(String[] args) {
        String s1 = null;
        if (s1 != null && s1.equals("hello")) {
            System.out.println("hello");
        }
    }
}

You can also put the object "hello" that must not be null in front: for example: if ("hello".equals(s)) { ... } .

Practise

Please write a program using if ... else to calculate body mass index (BMI) and print the result.

BMI = weight (kg) / height (m) squared

BMI results:

  • Too light: less than 18.5
  • Normal: 18.5 ~ 25
  • Overweight: 25 ~ 28
  • Obesity: 28 ~ 32
  • Very obese: above 32

Summary

if ... else can do conditional judgment, else is optional;

It is not recommended to omit the curly braces {} ;

When concatenating multiple if ... else special attention should be paid to the order of judgment;

Pay attention to the boundary conditions of if ;

It should be noted that the == operator cannot be used directly to determine equality of floating point numbers;

To determine the equality of reference types, use equals() , and be careful to avoid NullPointerException .

If Statement has loaded