5.3. The Java API

You will need to be able to use that Java class library, also called the Java Application Program Interface, or API.

The API is broken up into packages. For example, one of the packages is called java.math. You refer to a class by the package that it belongs to. Class java.math.Math is the class called Math in package java.math.

In a Java program, you refer to classes by their full names. For example,

  double q = java.math.Math.sqrt(2.0);
uses the method sqrt that is part of class java.math.Math.

Pay attention to the case of letters. In the Java API, package names start with lower case letters. Class names start with upper case letters. Most method names start with lower case letters


Imports

It is clumsy for the sqrt function to have such a long name, java.math.Math.sqrt. You can shorten it by doing an import Import

  import java.math.Math;
allows you to write Math to mean java.math.Math. So you can write
  double q = Math.sqrt(2.0);
Import
  import java.math.*;
imports all classes in package java.math.

Write imports at the beginning of a Java file, before the first class.


Package java.lang

Every Java program implicitly imports all classes in package java.lang. For example, class java.lang.String can be refered to as String, without the package name.


Static imports

You can shorten some method names further. Import line

  import static java.math.Math.sqrt;
allows you to write
  double q = sqrt(2.0);
where you use short name sqrt. Import line
  import static java.math.Math.*;
imports all methods whose name begin with java.math.Math.


Restrictions on imports

You can import a class name from a package or a static method in a class. But you cannot import an object.

For example, package java.lang contains a class called System. You can use it for writing to the standard output, as follows.

  System.out.println("A string");
You can shorten that by doing a static import of class System.
  import static java.lang.System;
Now you can write
  out.println("A string");
But out is an object that is part of class System. You cannot import that, so you cannot shorten the name any further.