Check Positive or Negative Number in Java

thumbnail

In this tutorial, we well learn to check a given number is positive or negative. The problem can be solved using if else statement in java. The logic to check a number whether a given number is positive or negative can be see at the below:

  • If a number is greater than zero, it is a positive number.
  • If a number is less than zero, it is a negative number.
  • If a number equals to zero, it is zero.

Example: Check Positive or Negative Number in Java

public class PositiveNegative {
    public static void main(String[] args) {
        double number = 45.6;
        // True when the number is greater than 0
        if (number > 0.0) {
            System.out.println(number + " is a positive number.");
        // True when number is less than 0
        } else if ( number < 0.0) {
            System.out.println(number + " is a negative number.");
        // if both test expression is evaluated to False
        } else {
            System.out.println(number + " is 0.");
        }
    }
}

The output will be:

45.6 is a positive number.

If you change the number value to any negative number (for example: -45.6), the output will be:

-45.6 is a negative number.

To see more amazing tutorial, you can see through this link.

Back To Top