Java Reference
In-Depth Information
TIP:
(continued)
It would be convenient to be able to write static method invocations in the following
simple form:
toUpperCase(firstCharacter)
instead of having to write the following longer version (taken from Display 5.9):
Character.toUpperCase(firstCharacter)
If you add the following static
import
statement to the start of your program, you can
then write the invocation of
toUpperCase
in the desired shorter way:
import static
java.lang.Character.toUpperCase;
The class
Character
is in the Java package
java.lang
. Note that you need to give
the package name as well as the class name, just as you did with ordinary
import
statements, such as the above
import
statement for the class
Scanner
in the
java.util
package.
The package
java.lang
is imported automatically. So you can, for example, use the
method
Character.toUpperCase
without any
import
statement of any kind. But note
that there is nothing special about the package
java.lang
when it comes to static
import
statements. If you want to use the abbreviated form
toUpperCase
, you must give
a static
import
statement.
If you use the following form of the static
import
statement, then your code can use
the name of any static method in the class
Character
without the preface of
Character
and a dot.
import static
java.lang.Character.*;
For example, consider the program in Display 5.9. If you replace
import
java.util.Scanner;
with either
import
java.util.Scanner;
import static
java.lang.Character.toUpperCase;
or
import
java.util.Scanner;
import static
java.lang.Character.*;
then you can change the statement
sentence = Character.toUpperCase(firstCharacter)
+ sentence.substring(1);