Check Positive or Negative in Java
Problem
Every integer is exactly one of three things: positive, negative, or zero, decided by comparing it against zero.
Given an integer, determine whether it is positive, negative, or zero.
Java Program
public class PositiveOrNegative {
public static void main(String[] args) {
int n = -7;
if (n > 0) {
System.out.println(n + " is positive");
} else if (n < 0) {
System.out.println(n + " is negative");
} else {
System.out.println(n + " is zero"); // neither check matched, so n must be exactly zero
}
}
}Output
Core Logic
Testing the number against zero, first for greater-than and then for less-than, separates all three outcomes in order.
- 1
n > 0is checked first — if it holds, the number is positive. - 2
n < 0is checked next — if the first check failed but this one holds, the number is negative. - 3If neither check holds,
nmust be exactly zero, and the finalelsebranch reports that.
n = -7, the first check fails since -7 isn't greater than 0, but the second check succeeds, so it's reported as negative.Key Point: Checking greater-than and less-than separately, rather than a single equality test, is what lets zero fall out as its own distinct case in the final else branch.
Key Concepts
Approach 2: Using Integer.signum()
public class PositiveOrNegativeSignum {
public static void main(String[] args) {
int n = -7;
// signum() normalizes any int down to exactly -1, 0, or 1
int sign = Integer.signum(n);
if (sign == 1) {
System.out.println(n + " is positive");
} else if (sign == -1) {
System.out.println(n + " is negative");
} else {
System.out.println(n + " is zero"); // signum() only ever returns 1, -1, or 0
}
}
}
Output
Core Logic
Java's Integer.signum() already reduces any integer down to exactly -1, 0, or 1, so branching on the sign becomes branching on one of three fixed values.
- 1
Integer.signum(n)normalizesnto1if it's positive,-1if it's negative, or0if it's exactly zero. - 2The same three-way if/else structure then branches on that normalized
signvalue instead of onndirectly.
Integer.signum(-7) returns -1, so the sign == -1 branch fires and reports the number as negative.Key Point: Integer.signum() is most useful when the sign itself needs to be compared, stored, or passed around as a value — like sorting by sign — rather than for a single one-off check.