Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What are the 22 possible values of x where x== -x (true)?

Tags:

java

Recently this question asked in Java interview. Tried and searched the solution but can't find. kindly, comment the solution if anybody knows. It would be helpful.

like image 930
Yaswanthkumar Avatar asked Jul 16 '21 06:07

Yaswanthkumar


1 Answers

Zeroes in the numeric basic types. Float and double have two zeroes each. That's nine values. Then there's MIN_VALUE for int and long. That's eleven.

So:

int x = 0;
int x = Integer.MIN_VALUE;
long x = 0;
long x = Long.MIN_VALUE;
byte x = 0;
short x = 0;
char x = 0;
double x = 0.0;
double x = -0.0;
float x = 0f;
float x = -0f;

Then each of those values wrapped as an object:

Integer x = 0;
Integer x = Integer.MIN_VALUE;
Long x = 0L;
Long x = Long.MIN_VALUE;
Byte x = 0;
Short x = 0;
Character x = 0;
Double x = 0.0;
Double x = -0.0;
Float x = 0f;
Float x = -0f;

That's 22 total.

(I wouldn't have called the objects more values. They're the same 11 values again but wrapped in objects. But if you're supposed to find 22 total, I think this must be it.)

Note that for smaller integral types, like short, performing -x would widen them to an int, so x==-x does not work for Short.MIN_VALUE.

x==-x evaluates as true for floating-point zeroes, because even though positive zero and negative zero are different values, they are regarded as equal to each other.

like image 125
khelwood Avatar answered Oct 25 '22 10:10

khelwood