How to check if a number is positive, negative, or zero in Java
Overview
We can check if a value is positive, negative, or zero in Java using the conditional statements if else and else if. The logic is to check first if the number is greater than 0 (positive). The second condition is to check if it is less than zero (negative). The last condition is to say that it is a zero because none of the other conditions are true.
Syntax
if(number > 0)// number is positiveelse if(number < 0)// number is negativeelse// number is equal to zero
Syntax for checking if a number is positive, negative or zero in Java
Parameters
number: This is the number we want to check to see if it is positive, negative, or zero.
Example
class HelloWorld {static void checkNumber(int num){//check if number is positive, negative or zeroif(num>0)System.out.println(num + " is POSITIVE NUMBER.");else if(num<0)System.out.println(num + " is NEGATIVE NUMBER.");elseSystem.out.println(num + " is a ZERO.");}public static void main( String args[] ) {// create some number valuesint no1 = 20;int no2 = 0;int no3 = -100;int no4 = 4 * -1;// invoke functioncheckNumber(no1);checkNumber(no2);checkNumber(no3);checkNumber(no4);}}
Explanation
- Line 2: We create a method called
checkNumber()which takes a number as a parameter, checks if it is positive, negative, or zero, then tells us what it is. - Lines 13–16: We create some integer values that we want to check to see if they are positive, negative, or zero.
- Lines 19–22: With the
checkNumber()method we created, we use it to check if the numbers we created are positive, negative, or zero. Then we print the results to the console.