Java – Check if a Number is Positive or Negative

A number is said to be positive if it is greater than zero and negative if it is less than zero.

In this tutorial, we shall write a Java program, to check if a given number is positive or negative, using greater-than comparison operator.

Check Positive or Negative Number using simple If Statement

To check if a number is positive, use comparison operator: greater than (>) that accepts the number and zero as operands. If number is greater than zero, it returns true, else it returns false.

To check if a number is negative, use comparison operator: less than (<) that accepts the number and zero as operands. If number is less than zero, it returns true, else it returns false.

PositiveNegative.java

```/**
* Java Program - Check if Number is Positive or Negative
*/

public class PositiveNegative {

public static void main(String[] args) {
//number
int num = 8;

//check if number is positive
if(num > 0) {
System.out.println(num+" is positive.");
}

//check if number is negative
if(num < 0) {
System.out.println(num+" is negative.");
}
}
}```

Output

`8 is positive.`

Check Positive or Negative Number using If-Else-If Statement

We shall use the same logic from above example, to check if given number is positive and negative. But with one change, which is: using if-else-if statement instead of simple if statement. We are using if-else-if statement because, if a number is positive, there is no chance that it could be negative and vice versa.

Also, we shall include an else block. If the number is neither positive nor negative, then else block will execute.

PositiveNegative.java

```/**
* Java Program - Check if Number is Positive or Negative
*/

public class PositiveNegative {

public static void main(String[] args) {
//number
int num = -9;

//check if number is positive or negative
if(num > 0) {
System.out.println(num+" is positive.");
} else if(num < 0) {
System.out.println(num+" is negative.");
} else {
System.out.println(num+" is zero.");
}
}
}```

Output

`-9 is negative.`

Conclusion

In this Java Tutorial, we learned how to check if a number is positive or negative using Java comparison operators: less than and greater than.