Java Program to Check Whether a Number is Positive or Negative
A number is positive if it is greater than zero (number > 0), for example 1, 2.5 or 300. It is negative if it is less than zero (number < 0), for example -1 or -42.7. Zero is neither positive nor negative, so a correct program needs three branches, not two.
1. Positive, Negative or Zero Using if-else-if
An if-else-if chain checks the conditions one after another and runs only the first branch that matches.
public class PositiveNegative {
public static void main(String[] args) {
int[] numbers = {50, -20, 0};
for (int number : numbers) {
if (number > 0) {
System.out.println(number + " is a positive number.");
} else if (number < 0) {
System.out.println(number + " is a negative number.");
} else {
System.out.println(number + " is zero, neither positive nor negative.");
}
}
}
}
Output
50 is a positive number. -20 is a negative number. 0 is zero, neither positive nor negative.
2. Positive or Negative with User Input
This version reads a double, so it also works for decimal numbers such as -286.76.
import java.util.Scanner;
public class PositiveNegativeInput {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a number: ");
double number = scanner.nextDouble();
scanner.close();
if (number > 0) {
System.out.println(number + " is a positive number.");
} else if (number < 0) {
System.out.println(number + " is a negative number.");
} else {
System.out.println("The number is zero.");
}
}
}
Output 1
Enter a number: 51 51.0 is a positive number.
Output 2
Enter a number: -286.76 -286.76 is a negative number.
3. Positive or Negative Using Integer.signum()
Integer.signum(n) returns 1 for positive numbers, -1 for negative numbers and 0 for zero. A switch on that value covers all three cases.
public class PositiveNegativeSignum {
public static void main(String[] args) {
int[] numbers = {7, -3, 0};
for (int number : numbers) {
String result = switch (Integer.signum(number)) {
case 1 -> "positive";
case -1 -> "negative";
default -> "zero";
};
System.out.println(number + " is " + result);
}
}
}
Output
7 is positive -3 is negative 0 is zero
4. Summary
- A number is positive if
number > 0and negative ifnumber < 0. - Zero is neither, so handle it in its own branch.
- Read a
doubleto accept decimal numbers as well as whole numbers. Integer.signum()andMath.signum()return the sign of a number as 1, -1 or 0.
Related Programs
Was this tutorial helpful?