Java Reference
In-Depth Information
One package requires no import statement. The package java.lang contains classes
that are fundamental to Java programming. These classes are so basic that the package
is always imported automatically. Any class in java.lang does not need an import
statement to make it available to your code. So, when we say that a class is in the pack-
age java.lang , you can simply use that class in your program without needing any
import statement. For example, the class String is in the java.lang package, so you
can use it without any import statement.
More material on packages is covered in Chapter 5.
java.lang
Self-Test Exercises
8. What output is produced by the following code? (Assume a proper import state-
ment has been given.)
NumberFormat exerciseFormatter =
NumberFormat.getCurrencyInstance(Locale.US);
double d1 = 1.2345, d2 = 15.67890;
System.out.println(exerciseFormatter.format(d1));
System.out.println(exerciseFormatter.format(d2));
9. Suppose the class Robot is a part of the standard Java libraries and is in the pack-
age named java.awt . What import statement do you need to make the class
Robot available to your program or other class?
The DecimalFormat Class
System.out.println will let you output numbers but has no facilities to format the
numbers. If you want to output a number in a specific format, such as having a specified
number of digits after the decimal point, then you must convert the number to a string
that shows the number in the desired format and then use System.out.println to out-
put the string. We have seen one way to accomplish this for amounts of money. The class
DecimalFormat provides a versatile facility to format numbers in a variety of ways.
The class DecimalFormat is in the Java package named java.text . So you must add
the following (or something similar) to the beginning of the file with your program or
other class that uses the class DecimalFormat :
import
import java.text.DecimalFormat;
An object of the class DecimalFormat has a number of different methods that can
be used to produce numeral strings in various formats. In this subsection, we discuss
one of these methods, which is named format . The general approach to using the
format method is discussed in the following pages.
Create an object of the class DecimalFormat , using a String Pattern as follows:
patterns
DecimalFormat Variable_Name = new DecimalFormat( Pattern );
Search WWH ::




Custom Search