Packages and Imports

Site Admin · 11 Sep 2026 · 12 views

What Is a Package?

A package is a folder-like namespace that groups related classes. It prevents name clashes (two classes called Utils in different packages can coexist) and keeps large projects organised.

Declaring a Package

The package statement must be the very first line of a java file.

// file: src/com/myapp/Utils.java
package com.myapp;

public class Utils {
    public static int doubleIt(int n) { return n * 2; }
}

Using Classes from Other Packages

Import the class once at the top, then use its simple name everywhere.

import com.myapp.Utils;
import java.util.Scanner;   // single class
import java.util.*;          // all classes of the package (wildcard)

public class Main {
    public static void main(String[] args) {
        System.out.println(Utils.doubleIt(21)); // 42
    }
}

Classes in the Same Package

Classes in the same package need no import at all - they see each other directly.

Fully Qualified Names

You can skip the import and write the full name each time:

com.myapp.Utils.doubleIt(10);

This is verbose, so imports are preferred. The classes of java.lang (String, Math, System) are imported automatically.

Built-in Package Highlights

  • java.lang - core classes, auto-imported.
  • java.util - collections, Scanner, dates, random.
  • java.io, java.nio - file and stream I/O.
  • java.net - networking.
  • java.time - modern date and time.

Key Points

  • Packages organise code and prevent name collisions.
  • import lets you use simple names.
  • Reverse-domain names (com.mycompany.app) are the convention.
Share this post:

Comments (0)

Please login or register to comment.