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

A simple Java program that shows the functionality of an if-else statement.

Code Explanation

LineDescription
3Initializes the variable a of type int with the value 8
5 – 6If the value of the variable a is greater than 0, the string “positive” is output
7 – 8If the value of the variable a is 0, the string “0” is output
9 – 10Otherwise the string “negative” will be output
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