How to Check Positive or Negative Number in Java
The Challenge
Determine if a number is positive, negative, or zero!
Solution
java
public class Main {
public static void main(String[] args) {
int number = -5;
if (number > 0) {
System.out.println(number + " is positive");
} else if (number < 0) {
System.out.println(number + " is negative");
} else {
System.out.println("Number is zero");
}
}
}
// Output: -5 is negativeUsing Ternary Operator
java
int number = 10;
String result = (number > 0) ? "positive" :
(number < 0) ? "negative" : "zero";
System.out.println(number + " is " + result);
// Output: 10 is positiveUsing Method
java
public static String checkNumber(int num) {
if (num > 0) return "positive";
else if (num < 0) return "negative";
else return "zero";
}
// Usage
System.out.println(checkNumber(15)); // positive
System.out.println(checkNumber(-7)); // negative
System.out.println(checkNumber(0)); // zeroDid You Know?
In Java, zero is neither positive nor negative. It's a neutral number that separates positive and negative numbers on the number line!
Pro Tip
Use Math.signum() for a concise approach:
java
double result = Math.signum(-5);
// Returns: -1.0 (negative), 0.0 (zero), or 1.0 (positive)Real-World Use Cases
- Banking: Check if account balance is positive or negative
- Temperature: Determine if temperature is above or below freezing
- Gaming: Check if player score is positive or negative
- Data analysis: Classify numerical data
›Short versionOpen if you only have a minute.
- Three outcomes need three branches: greater than zero, less than zero, and equal to zero.
- An if/else that only tests > 0 labels zero as negative.
- Every comparison with NaN is false, including NaN == 0.
- -0.0 compares equal to 0.0. Double.compare distinguishes the two bit patterns.
Positive, negative, or zero
Classify a numeric value as positive, negative, or zero.
Working approach
- Test > 0, then < 0, and leave equality as the remaining case.
- For a double, reject NaN before the comparisons.
- Keep the classification separate from printing.
Walk the sample
- Input -8
- num > 0 is false
- num < 0 is true
- The value is negative
The trap
Double.NaN is not positive, not negative, and not zero. A chain of comparisons falls through to whichever branch you wrote last.
java
static String sign(double value) {
if (Double.isNaN(value)) {
return "not a number";
}
if (value > 0) {
return "positive";
}
if (value < 0) {
return "negative";
}
return "zero";
}Which branch does Double.NaN take in if (n > 0) else if (n < 0) else?
Neither comparison is true. NaN falls into the else and is reported as zero unless you test Double.isNaN first.
NaN == NaN is also false. Equality is not a way to detect it.
Time O(1), space O(1).
Easy to get wrong
- Using one else and labeling zero as negative.
- Comparing a double without a NaN check.