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.
if(number > 0)// number is positiveelse if(number < 0)// number is negativeelse// number is equal to zero
number
: This is the number we want to check to see if it is positive, negative, or zero.
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);}}
checkNumber()
which takes a number as a parameter, checks if it is positive, negative, or zero, then tells us what it is.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.