Java Code Example: check if a number is positive or negative

The IfElseStatement Java program demonstrates the use of an if-else statement to conditionally execute code based on multiple conditions.

In the program, there is an integer variable a that is initialized to 8. The if-else statement checks the value of a and executes the appropriate code block based on the following conditions:

  • If a is greater than 0, the code block inside the first if statement is executed, which prints “positiv”.
  • If a is equal to 0, the code block inside the else if statement is executed, which prints “0”.
  • If a is less than 0, the code block inside the else statement is executed, which prints “negative”.

In this case, a is greater than 0, so the code block inside the first if statement is executed, and the output will be “positiv”.

public class IfElseStatement {
    public static void main(String[] args) {
        int a = 8;

        if (a > 0) {
            System.out.println("positiv");
        } else if (a == 0) {
            System.out.println("0");
        } else {
            System.out.println("negative");
        }
    }
}
Output
positiv

In summary, the program demonstrates how to use an if-else statement to conditionally execute code based on multiple conditions, and how to print output to the console using the System.out.println method.