Write a Java program to check if a number is positive or negative is one of the popular Java coding interview questions, it may look easy but programmers often fumble on this question. One of the tricky parts of this question is that Java has multiple data types 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 solutions work for int and long but may not work for floating-point numbers e.g. float and double.
This is also a tricky Java question, another tricky point is considering special cases like positive infinity, negative infinity, or NaN in the case of checking floating-point numbers. Things get more complicated when, as follow-up questions, the interviewer puts additional conditions such as you can not use relational operators, etc.
Nevertheless, Java provides several ways 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 the sign of the number in Java.
Also, basic knowledge of essential data structure and algorithms is a must for Java developers and that's why I suggest all Java programmers join these Data Structure and Algorithms courses to improve their knowledge and algorithms skills.
This is also a tricky Java question, another tricky point is considering special cases like positive infinity, negative infinity, or NaN in the case of checking floating-point numbers. Things get more complicated when, as follow-up questions, the interviewer puts additional conditions such as you can not use relational operators, etc.
Nevertheless, Java provides several ways 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 the sign of the number in Java.
Also, basic knowledge of essential data structure and algorithms is a must for Java developers and that's why I suggest all Java programmers join these Data Structure and Algorithms courses to improve their knowledge and algorithms skills.
Different ways to check if a number is positive or negative in Java
Here is a quick summary of different ways I can think of checking the sign of numbers and finding whether a number is positive or negative in Java. All these methods assume that you will put special check logic for handling special cases like positive infinity, negative infinity, and Nan and assuming zero on the positive side.
1. By Converting Number to String
Convert any number into String and get the first character, if it's equals to "-" then it's a negative number otherwise it's a positive one. Though this method will not work for float and double if a 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 the sign of number should work. Look at the 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
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 to get the 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 the sign of number like this.
2. By using Relational Operators in Java
Use relational operator to check if a number is positive or not, if number >=0 means a 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";
}
}
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
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 the relational operator to check the sign of a number in Java.
3. By Using the Bit Shift operator
This is an alternative way of checking if a number is positive or negative in Java and used if the Interviewer asks 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, the most significant bit represents a sign of number which should be 0 for a positive number and 1 for a negative number in binary format.
By using a bit shift operator or a proper mask you can check if the most significant bit is 1 or zero. Here is an 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";
}
}
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
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 the signum function of method argument means returns zero if an argument is zero, 1.0 if an argument is greater than zero, and -1.0 if the argument is less than zero. This is an 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 at all approaches, it seems using a relational operator seems the easiest and correct solution to finding out if a number is positive or negative. Don’t use the String approach, it's fragile and only works for some data types.
Related Java Programming Interview questions from Javarevisited Blog
By the way, what is your favorite coding question? do let us know in comments?
You can also compare the number with Math.abs(number)
ReplyDeleteThe 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.
ReplyDeleteYou'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.
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.
ReplyDelete@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.
ReplyDeleteJavin
@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.
ReplyDeleteWhy cant you just compare with 0 (zero)
ReplyDeleteboolean isPositive = number > 0;
ReplyDeleteInterview over.
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.
ReplyDeleteanother easy method is to use Scanner
ReplyDeletefirst 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");
}
}