Back to course

Organizing Code with Packages and Import Statements

Java Mastery: From Zero to Professional Developer (50-Lesson Journey)

Lesson 28: Organizing Code with Packages and Import Statements

Packages are Java's way of grouping related classes and interfaces together. They prevent naming conflicts and help control access.

1. Defining a Package

  • The package declaration must be the very first line of your Java source file (if present).
  • Conventionally, package names are all lowercase and use reversed domain names (e.g., com.mycompany.app).

java // File: com/mycompany/models/Car.java package com.mycompany.models;

public class Car { /* ... */ }

2. Default Package

If you don't specify a package, the class belongs to the default package. This is discouraged for real-world applications.

3. Importing Classes

When you want to use a class defined in a different package, you must use the import statement.

A. Importing a Specific Class

java import java.util.ArrayList;

// Now we can use ArrayList directly ArrayList list = new ArrayList();

B. Importing All Classes in a Package

Using the asterisk (*) imports all classes within that package, but not sub-packages.

java import java.util.*; // Imports ArrayList, HashMap, Scanner, etc.

Scanner scanner = new Scanner(System.in);

Note on java.lang: The java.lang package (which contains classes like String, System, and Math) is automatically imported into every Java program.

4. Fully Qualified Class Name (FQC)

If two packages contain classes with the same name, or if you choose not to import, you must use the Fully Qualified Class Name (FQC):

java // Using two different Date classes without import conflicts java.util.Date utilDate = new java.util.Date(); java.sql.Date sqlDate = new java.sql.Date(utilDate.getTime());