go to previous page   go to home page   go to next page highlighting
if ( 1_000_000_000L + 2_000_000_000L > 0 )
    System.out.println("Obviously True");
else
    System.out.println("What???");

Answer:

Obviously True

The L at the end of the integer literals makes them data type long.

The 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.


Data type 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. Look at the following:


 
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

The expected product, 35_000_000_000_000_000_000 is larger than the upper limit for long, +9×1018. So again, overflow happens.


QUESTION 3:

Here's an idea: why not use double to represent numbers?

double has the range (roughly) -1.7×10308 to +1.7×10308. Surely that is large enough.


go to previous page   go to home page   go to next page