(^602) | Multidimensional Arrays and Numeric Computation
Choosing a Numeric Data Type
A first encounter with all the numeric data types of Java may leave you feeling a bit overwhelmed.
To help in choosing an alternative, you may even feel tempted to toss a coin. You should resist this
temptation, because each data type exists for a reason. Here are some guidelines:
- In general,intis preferable.
As a rule, you should use floating-point types only when absolutely necessary—that is,
when you definitely need fractional values. Not only is floating-point arithmetic subject
to representational errors, but it is also significantly slower than integer arithmetic on
most computers.
For ordinary integer data, use intinstead of byteor short. It’s easy to make overflow er-
rors with these smaller data types. - Use longonly if the range of intvalues is too restrictive. Compared to int, the longtype
requires twice as much memory space. - The default floating-point type in Java is double. It should be used unless you are certain
that a problem can be solved with the lower precision of the floattype.
By following these guidelines, you’ll find that the simple types you use most often are int
and double, along with charfor character data and booleanfor Boolean data. Only rarely do you
need the longer or shorter variations of these fundamental types.
12.6 Decimal Format Type
To give more precise control over the formatting of numbers, Java provides a class called
DecimalFormatthat is part of a package called java.text. The DecimalFormatclass allows us to
create patterns that can be used to format numbers for output. These patterns take the form
of strings, which are made up of characters that represent the parts of a formatted number.
For example, the pattern
"###,###"
indicates that a number should be formatted with a maximum of six decimal digits. When
the number contains more than three digits, a comma should be used to separate the thou-
sands from the rest of the number.
We must follow four steps to use DecimalFormatpatterns to format numbers:
1.importjava.text.*;