Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Java reference

import / package

package sets the file's package, import lets you use short names of classes from other packages.

Available since: Java 1.0

Syntax

package name;  /  import package.Type;  /  import static package.Type.member;  /  import module name;

Examples

Importing a class from a module that a compact source file does not import by itself (java.logging):

import java.util.logging.Logger;
 
void main() {
    Logger log = Logger.getLogger("shop");
    IO.println(log.getName());
}

Output:

shop

A static import lets you use static members without the class name:

import static java.lang.Math.PI;
import static java.lang.Math.sqrt;
 
void main() {
    IO.println(sqrt(16));
    IO.println(PI > 3);
}

Output:

4.0
true

import module (Java 25) imports all public packages of a module at once:

import module java.sql;
 
void main() {
    IO.println(Types.VARCHAR);
}

Output:

12

An ordinary project file: package comes first, then the imports. The folders repeat the package name:

// src/main/java/shop/model/Order.java
package shop.model;
 
import java.math.BigDecimal;
import java.util.List;
 
public record Order(int id, List<String> items, BigDecimal total) {}

Notes

The java.lang package (String, Math, Integer) is always imported, and a compact source file with void main() also imports the whole java.base module (java.util, java.io, java.time and others). A star import import java.util.*; brings in every class of the package, but not nested packages. An import does not load code or affect speed — it only shortens names. If two packages have classes with the same name, such as java.util.Date and java.sql.Date, write one of them with its full name.

See also

  • public / protected / private — Access modifiers control where a class, field, method or constructor is visible from.
  • module / requires / exports — A module declaration in module-info.java: which modules it needs and which packages it exposes to others.
  • class — Declares a class — a description of objects: their fields and methods.
  • static — Makes a field or method belong to the class itself rather than to each object.

In the tutorial

  • Packages and access modifiers — Packages and import in Java, the public, protected and private modifiers and default access, building and running a multi-file project.

Thanks for reading!

Donate to the site — we work hard for you.