AI Hints
Home›Java Tutorial›StringBuilder, Dates and Times, Packages and Imports
Java · Lesson 111 of 120

Packages and Imports

Organise your code.

⏱ 2 min read▶ Video at 2:21:37🎓 Free
Watch this lesson in the Java courseWatch on YouTube ↗Full Java course

Big programs have hundreds of classes. Packages group them into folders, and import lets one class use another from a different package.

  • Hundreds of classes
  • Packages are folders
  • import connects them

shop/Product.java

The first line says this class belongs to the package called shop. The file lives in a folder with the same name, shop. Public makes the class usable from other packages.

shop/Product.javajava
package shop;

public class Product {
    private final String name;
    private final double price;
    public Product(String name, double price) { this.name = name; this.price = price; }
    public String label() { return name + " (" + price + ")"; }
}

Importing it

Import shop dot Product lets Main use Product by its short name. We've imported from java dot util many times already. Import static brings in a static method, so we can write max instead of Math dot max. Run it. The product prints its label, and the tags print, with eight.

Main.javajava
import shop.Product;
import java.util.List;
import static java.lang.Math.max;
public class Main {
    public static void main(String[] args) {
        Product p = new Product("Lamp", 24.0);
        System.out.println(p.label());
        List<String> tags = List.of("home", "light");
        System.out.println(tags + " " + max(3, 8));
    }
}
Output
Lamp (24.0)
[home, light] 8
Also uses shop/Product.java
package shop;

public class Product {
    private final String name;
    private final double price;
    public Product(String name, double price) { this.name = name; this.price = price; }
    public String label() { return name + " (" + price + ")"; }
}

Package rules

Package names are lower case, often like a reversed website, such as com dot example dot shop. The folder structure must match the package name. Classes in java dot lang, like String and Math, are imported automatically.

keyvalue
Nameslower case: com.example.shop
Foldersmatch the package
importuse another package's class
Freejava.lang: String, Math

Summary

A package groups classes into a folder. Import lets you use classes from other packages. Next, we start our project, a to do list.

Key takeaways
  • package shop;
  • import shop.Product;
  • Folders match
Next up: Project: The Plan — what we will build