Wednesday, January 16, 2013

How to check if a Number is Positive or Negative in Java - Interview Question

Write a Java program to check if a number is positive or negative is one of the popular Java coding interview question, it may look easy but programmers often fumble on this question. One of the tricky part of this question is that Java has multiple data type to support numbers like byte, short, char, int, long, float and double, out of those all are signed except char, which can not represent negative numbers. Some solution work for int and long but may not work for floating point number e.g. float and double. This is also a tricky Java question, another tricky point is considering special case like positive infinity, negative infinity or NaN in case of checking floating point numbers. Things gets more complicated when, as followup questions, interviewer put additional conditions such as you can not use relational operator etc. Nevertheless Java provides several way to check if a number whether integer or floating point is positive or negative. In this Java tutorial, we will see such methods of checking sign of number in Java.

Different ways to check if number is positive or negative in Java

Java program to check if a number is positive or negative with exampleHere is quick summary of different ways I can think of checking sign of number and finding whether a number is positive or negative in Java. All these method assumes that you will put special check logic for handling special cases like positive infinity, negative infinity and Nan and assuming zero on positive side.

1) By Converting Number to String
Convert any number into String and get first character, if its equals to "-" then its negative number otherwise its
positive one. Though this method will not work for float and double, if number is represented in exponential form. This could be the case if you are dealing with large floating point numbers. For long and int this method of checking sign of number should work. Look at following example of string equivalent of minimum values of Integer, Long, Float and Double

System.out.println(Integer.MIN_VALUE);
System.out.println(Long.MIN_VALUE);
System.out.println(Float.MIN_VALUE);
System.out.println(Double.MIN_VALUE);

-2147483648
-9223372036854775808
1.4E-45
4.9E-324

Only Integer and Long can be checked getting first character and comparing with "-". See How to convert Integer to String and  Long to String in Java to convert these numbers into String. By the way this approach is fragile and should not be used in any production code, I have just shared it here because I have seen people checking sign of number like this.

2) By using Relational Operators in Java
Use relational operator to check if number is positive or not,  if number >=0 means number is positive if number<0 means number is negative in Java this should work for double and float as well but I haven't tested it for all values.

 public static String checkSignWithRelational(double number){
        if( number < 0){
            return "negative";
        }else {
            return "positive";
        }
 }

Testing:
System.out.println("0.0 is " + checkSignWithRelational(0.0));
System.out.println("2.0 is " + checkSignWithRelational(2.0));
System.out.println("-2.0 is " + checkSignWithRelational(-2.0));
System.out.println("Double.POSITIVE_INFINITY is " + checkSignWithRelational(Double.POSITIVE_INFINITY));
System.out.println("Double.NEGATIVE_INFINITY is " + checkSignWithRelational(Double.NEGATIVE_INFINITY));

Output
0.0 is positive
2.0 is positive
-2.0 is negative
Double.POSITIVE_INFINITY is positive
Double.NEGATIVE_INFINITY is negative

In my opinion this should be the right way to check whether a number is positive or negative in Java. Let me know if you guys have seen any issue using relational operator to check sign of a number in Java.

3) By Using Bit Shift operator
This is an alternative way of checking if a number is positive or negative in Java and used if Interviewer ask you not to use relational operators. Negative numbers in Java are represented using 2's complement method and since long and int are signed integer along with byte and short, most significant bit represent sign of number which should be 0 for positive number and 1 for negative number in binary format. By using bit shift operator or a proper mask you can check if most significant bit is 1 or zero. Here is example for checking int and long values :

  public static String checkSign(int number){
        if(number == 0) return "positive";
        if(number >> 31 != 0){
            return "negative";
        }else{
            return "positive";
        }
    }
 
    public static String checkSign(long number){
        if(number == 0) return "positive";
        if(number >> 63 != 0){
            return "negative";
        }else{
            return "positive";
        }
    }
Testing for checkSign(int) method
System.out.println("0 is " + checkSign(0));
System.out.println("2 is " + checkSign(2));
System.out.println("-2 is " + checkSign(-2));
System.out.println("Integer.MAX_VALUE is " + checkSign(Integer.MAX_VALUE));
System.out.println("Integer.MIN_VALUE is " + checkSign(Integer.MIN_VALUE));

Output
0 is positive
2 is positive
-2 is negative
Integer.MAX_VALUE is positive
Integer.MIN_VALUE is negative

This method can be extended to check double and float value by representing double and float values into long
using Double.longBitsToDouble() or Float.floatToIntBits(number).

4) Use Math.signum()
java.lang.Math provides a method called signum() which returns signum function of method argument means returns zero if argument is zero , 1.0 if argument is greater than zero and -1.0 if argument is less than zero. This is a overloaded method to accept float and double values.

That’s all on How to check if a number is positive or negative in Java. From looking all approaches, seems using relational operator seems most easy and correct solution to find out if number is positive or negative. Don’t use String approach, its fragile and only works for some data types. 

Related Java Programming Interview questions from Javarevisited Blog

9 comments :

alfasin said...

You can also compare the number with Math.abs(number)

Dave Conrad said...

The first suggestion, to use String conversion, is inane. It's an expensive way of doing something that can simply be done with a relational operator. But it's absurdly wrong to say it doesn't work for floating point values. Of course it does.

You're completely misusing Float.MIN_VALUE and Double.MIN_VALUE. They are not analogues of Integer.MIN_VALUE and Long.MIN_VALUE. They are the smallest POSITIVE values that can be stored in a float or a double without underflow. To get the largest NEGATIVE values of a float or double you would write -Float.MAX_VALUE and -Double.MAX_VALUE. With such ignorance of the basics on display, I find it troubling you are writing a blog that purports to give information about Java.

You also completely neglect to discuss the floating point value negative zero, which is the real sticking point between integral and floating point values when it comes to identifying negative numbers.

The less-than relational operator will say that -0.0 is not less than zero, while String conversion would say that it is. But what is the correct answer in this case? Why are you trying to check for negative numbers at all? Your requirements are not well defined.

Anonymous said...

You are kidding right? This is tricky? If I asked you this question in an interview and you answered it this way, the interview would be over immediately. No way I'd hire you.

Javin @ ClassLoader in Java said...

@Dave Conrad, my bad. Indeed Float.MIN_VALUE and Double.MIN_VALUE are smallest POSITIVE values they can precisely represent it. Another worth noting point is that Float and Double uses sign bit to represent positive and negative number value which is different than Integer's 2's complement way. Regarding -0.0f which is considered less than 0.0f by compareTo() of Float class is a special case and for interview purpose can be considered as zero and considered on positive side as per interviewer. Thank you for pointing these important details.

Javin

Javin @ print array java said...

@Anonymous, I won't say it tricky for everyone but I did see many tricky point here. One of them is Float.MIN_VALUE representing smallest positive number itself. It's not always you can do it using relational operator, sometime you got to do it using bitwise as well. Thanks for your comment.

Anonymous said...

Why cant you just compare with 0 (zero)

Anonymous said...

boolean isPositive = number > 0;

Interview over.

Parag said...

Can we use these methods to check if a double value is positive or negative? I mean checking floating point numbers e.g. float and double, I am not sure how they are represented in byte format in Java.

Kush said...

another easy method is to use Scanner
first import scanner then

public static void main(String[] args) {
int x;
System.out.println("Enter a number");
Scanner in = new Scanner(System.in);
x = in.nextInt();
if(x<0)
System.out.println("It is negative");
else
System.out.println("It is positive");
}
}

Post a Comment