'long' data type




Lets first compute the distance light travels using the 'int' data type to find out its drawbacks.

Computing the distance light travels using 'int' data type: 

class Light
{
    public static void main(String args[])
    {
         int lightspeed, days, seconds, distance;
     
         lightspeed = 186000;  // Approximate speed of light in miles per second
         days = 1000;

         seconds = days*24*60*60; // days x 24 hours x 60 minutes x 60 seconds
         distance = lightspeed*seconds; // compute distance

         System.out.print("In " + days);
         System.out.print(" days light will travel about ");
         System.out.println(distance + " miles.");
     }
}

Output of this program:

In 1000 days light will travel about -1367621632 miles. (Wrong output)

Reason for wrong output:

The int data type can hold that values of lightspeed, days and seconds variables (You can checkout by printing their values in the program and verify them using your system calculator), but int data type was not long enough to hold the value of distance variable. 




Lets try the above program with 'long' data type and find out how it resolves the above problem

Computing the distance light travels using 'long' data type: 

class Light
{
    public static void main(String args[])
    {
        long lightspeed, days, seconds, distance;
     
         lightspeed = 186000;  // Approximate speed of light in miles per second
         days = 1000;

         seconds = days*24*60*60; // days x 24 hours x 60 minutes x 60 seconds
         distance = lightspeed*seconds; // compute distance

         System.out.print("In " + days);
         System.out.print(" days light will travel about ");
         System.out.println(distance + " miles.");
     }
}

Output of this program:

In 1000 days light will travel about 160700000000 miles (Correct output)