if ( 1_000_000_000L + 2_000_000_000L > 0 ) System.out.println("Obviously True"); else System.out.println("What???");
Obviously True
The expected sum of 3 billion (1 billion + 2 billion) DOES correctly fit into an long
.
The literals in the if
are of type long
, so in this case overflow is avoided.
long
Data type long
uses 64 bits, which can express integers
int the range -9 * 1018
to +9 * 1018
But sometimes even that is not enough
long a = 5_000_000_000L ; long b = 7_000_000_000L ; System.out.println("The product of " + a + " and " + b + " is " + (a*b) ); - - - - - - - - - - - - -- - - - - - - - - - - - - The product of 5000000000 and 7000000000 is -1893488147419103232
Here's an idea: why not use double
to represent numbers?
double
has the range (roughly) -1.7E308 to 1.7E308.
Surely that is large enough.