In this Java program, we’ll learn how to Check if a Number is Positive or Negative in Java.
How to Check if a Number is Positive or Negative in JAVA?
Example 1: Check if a number is positive or negative using Math.signum() method.
RUN CODE SNIPPETimport java.util.Scanner;
import java.lang.Math.*;
public class Main
{
public static void main(String[] args)
{
double num, result;
Scanner sc = new Scanner(System.in);
System.out.print("Enter a number you want to check: ");
num = sc.nextDouble();
result=Math.signum(num);
System.out.print(result);
}
}OUTPUT
Enter a number you want to check: 50 1.0
Java Math class is a static method that accepts a parameter of double type.
If the argument is 1.0 then the number is >0, else if the argument is –1.0 then the number is <0.
Example 2: Check if a number is positive or negative using if. Else statement.
RUN CODE SNIPPETpublic class Main
{
public static void main(String[] args)
{
double number = -5.0;
if (number < 0.0)
System.out.println(number + " is a negative number.");
else if ( number > 0.0)
System.out.println(number + " is a positive number.");
else
System.out.println(number + " is 0.");
}
}OUTPUT
-5.0 is a negative number.