Check Whether a Number is Positive or Negative in Java

Exercise:

Write a Java Program to check whether a number is positive or negative.

Click Here to View the Solution!
public class PositiveNegative {
 
    public static void main(String[] args) {
 
        double number = 9.4;
 
        // checks if number is less than 0
        if (number < 0.0)
            System.out.println(number + " is a negative number.");
 
        // checks if number is greater than 0
        else if ( number > 0.0)
            System.out.println(number + " is a positive number.");
 
        // if both test if-statements evaluated to false
        else
            System.out.println(number + " is 0.");
    }
} 
Click Here to View the Output!
9.4 is a positive number.
Click Here to View the Explanation!
  • This program is used for finding out that whether a number is positive or negative by using the if…else statement in Java.
  • The value 9.4 is stored into a variable number. This number is then compared to 0 through the if…else statements in the following manner
    • If the value in the variable number is larger than 0, then the value will be considered positive.
    • If the value in the variable number is smaller than 0, then the value will be considered negative.
    • And finally, if the value in the variable number is equal to 0, the it will be considered as 0.
  • If the value is changed to -9.4, then by passing through the same program the result “-9.4 is a negative number” will be displayed on the screen.
%d bloggers like this: