Java Reference
In-Depth Information
Ask the Expert
Q :
Why does Java have different data types for integers and floating-point values?
That is, why aren't all numeric values just the same type?
A : Java supplies different data types so that you can write efficient programs. For ex-
ample, integer arithmetic is faster than floating-point calculations. Thus, if you don't
need fractional values, then you don't need to incur the overhead associated with
types float or double . Second, the amount of memory required for one type of data
might be less than that required for another. By supplying different types, Java en-
ables you to make best use of system resources. Finally, some algorithms require (or
at least benefit from) the use of a specific type of data. In general, Java supplies a
number of built-in types to give you the greatest flexibility.
Try This 1-1 Converting Gallons to Liters
Although the preceding sample programs illustrate several important features of the Java
language, they are not very useful. Even though you do not know much about Java at this
point, you can still put what you have learned to work to create a practical program. In this
project, we will create a program that converts gallons to liters. The program will work by
declaring two double variables. One will hold the number of the gallons, and the second
will hold the number of liters after the conversion. There are 3.7854 liters in a gallon. Thus,
to convert gallons to liters, the gallon value is multiplied by 3.7854. The program displays
both the number of gallons and the equivalent number of liters.
1. Create a new file called GalToLit.java .
2. Enter the following program into the file:
Search WWH ::




Custom Search