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 positive else if(number < 0) // number is negative else // 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 zero if(num>0) System.out.println(num + " is POSITIVE NUMBER."); else if(num<0) System.out.println(num + " is NEGATIVE NUMBER."); else System.out.println(num + " is a ZERO."); } public static void main( String args[] ) { // create some number values int no1 = 20; int no2 = 0; int no3 = -100; int no4 = 4 * -1; // invoke function checkNumber(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.RELATED TAGS
CONTRIBUTOR
View all Courses