Java ยท Chapter 31 of 42

Java Packages

A package is a namespace that groups related classes and interfaces, helping organize large codebases and avoid naming conflicts. Package names typically follow a reversed domain convention, like com.example.myapp.

You use `package` at the top of a file to declare its package, and `import` to use classes from other packages.

Syntax
package com.example.myapp;
import java.util.ArrayList;

Declaring and importing packages

The `package` statement must be the first line in a Java file (aside from comments). `import` statements bring in classes from other packages so you can use their simple names.

Built-in packages

java.lang is imported automatically. java.util provides collections, java.io provides file/stream handling, and many more standard packages exist.

Example 1 (java)
import java.util.ArrayList;

public class Main {
  public static void main(String[] args) {
    ArrayList<String> list = new ArrayList<>();
    list.add("Java");
    System.out.println(list);
  }
}
Output
[Java]

ArrayList is imported from java.util and used to store and print a list.

Key points

  • Packages organize related classes and avoid naming conflicts.
  • package must be the first statement in a file.
  • import brings in classes from other packages.
  • java.lang is imported automatically into every file.
๐Ÿ’ก Note: Following the reversed-domain-name convention for package names avoids collisions between organizations.

๐Ÿ“ Quick Quiz

1. What is java.lang's import status?

2. What keyword brings in a class from another package?

3. Where must the package statement appear?