Import Statements

Kinds of Imports

FormExampleImports
Single typeimport java.util.List;one class (preferred)
On demandimport java.util.*;all classes in that package (not sub-packages)
Staticimport static java.lang.Math.PI;a static member
Static on demandimport static java.lang.Math.*;all static members
Fully qualifiedjava.util.Date d;no import needed

Using Imports

Example

Static imports let you write sqrt and PI without the Math. prefix. A fully qualified name avoids a clash between java.util.List and java.awt.List.

import java.util.ArrayList;
import java.util.List;
import static java.lang.Math.PI;
import static java.lang.Math.sqrt;

public class Main {
    public static void main(String[] args) {
        List<String> cities = new ArrayList<>();
        cities.add("Pune");
        cities.add("Chennai");
        System.out.println(cities);

        System.out.println("sqrt(144) = " + sqrt(144));
        System.out.printf("Circle area r=2: %.2f%n", PI * 2 * 2);

        java.awt.List awtList = new java.awt.List();   // fully qualified to avoid the clash
        System.out.println(awtList.getClass().getName());
    }
}

Output

[Pune, Chennai]
sqrt(144) = 12.0
Circle area r=2: 12.57
java.awt.List

Tips

  • java.lang (String, Math, Integer, System) is imported automatically.
  • Imports do not affect performance; they are only a compile-time shortcut.
  • Prefer single-type imports. IDEs organise them for you (IntelliJ: Ctrl+Alt+O).
  • Use static imports sparingly, mainly for constants and test assertions (assertEquals).