Programming and Problem Solving with Java

(やまだぃちぅ) #1
3.2 Numeric Data Types | 105

One caution about integer literals in Java: A literal constant beginning with a zero is as-
sumed to be an octal (base–8) number instead of a decimal (base–10) number. For exam-
ple, if you write


015


the Java compiler takes it to mean the decimal number 13. If you aren’t familiar with the oc-
tal number system, don’t worry about why an octal 15 is the same as a decimal 13. The im-
portant thing to remember is not to start a decimal integer literal with a zero (unless you want
the number 0, which is the same in both octal and decimal).


Floating-Point Types


We use floating-point types (or floating types) to represent real numbers. Floating-point
numbers have an integer part and a fractional part, with a decimal point in between. Either
the integer part or the fractional part, but not both, may be missing. Here are some examples:


18.0 127.54 0.57 4. 193145.8523 .8


Starting 0.57with a 0 does not make it an octal number. Only with integer values does a
leading 0 indicate an octal number.
Just as the integral types in Java come in different sizes (byte,short,int, andlong), so
do the floating-point types. In increasing order of size, the floating-point types arefloat
anddouble(meaning double precision). Thedoubletype gives us a wider range of values and
more precision (the number of significant digits in the number) than thefloattype, but
at the expense of twice the memory space to hold the number. In Java,intandfloatval-
ues take up 32 bits of memory space, whereas bothlonganddoubletake up 64 bits of mem-
ory space.
Floating-point values also can have an exponent, as in scientific notation. (In scientific
notation, a number is written as a value multiplied by 10 to some power.) Instead of writing
3.504  1012 , in Java we would write 3.504E12. The E(you can also use e) means “exponent of
base 10.”The number preceding the letter Edoesn’t need to include a decimal point. Here are
some examples of floating-point numbers in scientific notation:


1.74536E–12 3.652442E4 7E20 –8.01994E–23


A floatvalue can represent any 7-digit decimal number with an exponent in the range
of –45through 38 .A doublevalue can represent any 15-digit decimal number with an expo-
nent ranging from –324to 308.
In Java, the compiler automatically assumes that floating-point literals of the form
shown here are of type double. To write a literal of type float, you must end the number with
the letter F(or f). Here are some examples of floating-point literals:

Free download pdf