English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Java Basic Tutorial

Java Flow Control

Java Array

Java Object-Oriented (I)

Java Object-Oriented (II)

Java Object-Oriented (III)

Java Exception Handling

Java List (List)

Java Queue (Queue)

Java Map Collection

Java Set Collection

Java Input Output (I/O)

Java Reader/Writer

Java Other Topics

Java program to check if a number is positive or negative

Java Comprehensive Examples

In this program, you will learn how to check if a given number is positive or negative. This is done by using if else statements in Java.

Example: Use if else to check if a number is positive or negative

public class PositiveNegative {
    public static void main(String[] args) {
        double number = 12.3;
        //If number is less than 0, it is true
        if (number < 0.0)
            System.out.println(number + " is a negative number.");
        //If number is greater than 0, return true
        else if ( number > 0.0)
            System.out.println(number + " is a positive number.");
        // If both test expressions are calculated as false
        else
            System.out.println(number + " is 0.");
    }
}

When running the program, the output is:

12.3 It is a positive number.

If the value is changed to a negative number (for example-12.3),then the output is:

-12.3 It is a negative number.

In the above program, by comparing the variable number with 0, it can be clearly seen whether the variable number is positive or negative.

If unsure, please follow the following steps:

  • If the number is greater than zero, it is a positive number.

  • If the number is less than zero, it is a negative number.

  • If the number is zero, it is zero.

Java Comprehensive Examples