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
?
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 BigInteger
s that would convert to Long.MIN_VALUE
AND Long.MAX_VALUE
themselves, respectively, when longValue()
is called.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With