Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Integer.MAX_VALUE and Integer.MIN_VALUE

Tags:

java

Following code

BigInteger number=new BigInteger("2154789654785210095153123254756845");
boolean b=number.longValue()>Long.MIN_VALUE;
boolean c=number.longValue()<Long.MAX_VALUE;
boolean d=number.longValue()>=Integer.MIN_VALUE;
boolean e=number.longValue()<=Integer.MAX_VALUE;
System.out.println(""+b);
System.out.println(""+c);
System.out.println(""+d);
System.out.println(""+e);

generates output

true
true
false
true

Keeping in mind that after achieving MAX_VALUE in Integer,value goes back to MIN_VALUE and loops again, if a value is <=Integer.MAX_VALUE, then it must be >=Integer.MIN_VALUE, then why does boolean variable d returns false?

like image 526
prateek tomar Avatar asked Dec 15 '22 12:12

prateek tomar


1 Answers

This can be explained once we understand what longValue() is returning.

Converts this BigInteger to a long. This conversion is analogous to a narrowing primitive conversion from long to int as defined in section 5.1.3 of The Java™ Language Specification: if this BigInteger is too big to fit in a long, only the low-order 64 bits are returned. Note that this conversion can lose information about the overall magnitude of the BigInteger value as well as return a result with the opposite sign.

Printing the value of this variable yields -4694333933485660691, a value that is certainly a legal long value but is far less than Integer.MIN_VALUE (which is implicitly converted to a long here), so false is correct for the d printout.

Both the b and c outputs are true because the value -4694333933485660691 is greater than Long.MIN_VALUE, and because the value -4694333933485660691 is less than Long.MAX_VALUE. The only values that would print false for b and c are those BigIntegers that would convert to Long.MIN_VALUE AND Long.MAX_VALUE themselves, respectively, when longValue() is called.

like image 122
rgettman Avatar answered Dec 21 '22 09:12

rgettman