Java Program to Check if a Given Integer is Positive or Negative
Here, the task is to check whether the given integer number is positive or negative. Below are some basic properties of a number.
- If the Integer is greater than zero then it is a positive integer.
- If the number is less than zero then it is a negative integer.
- If the number is equal to zero then it is neither negative nor positive.
Input: X = 12 Output: Positive Explanation: Value of X is greater than 0 so it is Positive. Input: x = -5 Output: Negative Explanation: Value of X less than 0 so it is negative.
Approach 1: Using Relational operator we can check whether an integer is positive or negative.
Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.
- If number>0 then the number is positive.
- If number<0 then the number is negative.
- If a number is neither positive nor negative, the number is equal to 0.
Below is the java implementation of the above approach:
912 is Positive
Approach 2: Using Integer.signum() Method
Java Integer class provides an inbuilt function signum() to check if a number is positive or negative. It is a static method that accepts a parameter of integer type.
- It returns 0, if the argument is 0.
- It returns 1, if the argument>0.
- It returns -1, if the argument<0.
public static int signum(int i)
Below is the java implementation of the above method.
-125 is Negative
Approach 3 : Using Bit Shift operator
In Java, the integers are stored in the 2’s complement. We know that the highest bit of any negative number is 1, and the highest bit of any other number is 0.
Bit shift operator (Val>>31) copies the highest bit to every other bit. Therefore, the negative number becomes 11111111 11111111 11111111 11111111, and the positive or zero numbers become 00000000 00000000 00000000 00000000.
After this we can use & operator to check whether a number is positive or negative.
- If ((Val>>31) & 1) is 1 then the number will be negative.
- If ((Val>>31) & 1) is 0 then the number will be positive.
Note: It considers 0 as a positive number.
Below is the Java implementation of the above approach:
-15 is Negative