How to Check if a Number Is Positive or Negative in Java
Check if a Number is Positive or Negative in Java
When learning the Java programming language, it's important to understand how to determine whether a number is positive or negative. Knowing when to use a positive or negative integer can be useful when writing algorithms or creating mathematical equations.
In this tutorial, we'll discuss how to check if a number is positive or negative in Java. We'll also look at some examples to help you better understand this concept.
Checking if a Number is Positive or Negative with an If Statement
The simplest way to check if a number is positive or negative is to use an if statement. For example, consider the following code:
int myNum = 10; if (myNum > 0) { System.out.println("The number is positive."); } else { System.out.println("The number is negative."); }
In this example, we check if the value of the myNum
variable is greater than 0. If it is, we print out a message saying that the number is positive. Otherwise, we print out a message saying that the number is negative.
Using Math.signum()
Another way to check if a number is positive or negative is by using the Math.signum()
method. This method takes one argument, which is a real number, and returns 1 if the number is positive, 0 if the number is 0, and -1 if the number is negative.
For example, consider the following code:
double myNum = -10.5; // Using Math.signum() to check the sign of a number int result = Math.signum(myNum); if (result == 1) { System.out.println("The number is positive."); } else if (result == 0) { System.out.println("The number is zero."); } else { System.out.println("The number is negative."); }
In this example, we use the Math.signum()
method to check the sign of the myNum
variable. If it returns 1, we print out a message saying that the number is positive. If it returns 0, we print out a message saying that the number is zero. Otherwise, we print out a message saying that the number is negative.
Conclusion
In this tutorial, we discussed how to check if a number is positive or negative in Java. We looked at two different approaches for doing this: using an if statement and using the Math.signum()
method.
Now you have the knowledge you need to check if a number is positive or negative in your own Java programs!