JOOPs Through Java
All lessons

Unit 5 · Applying Java OOP · 7 min

Packages

A package is a namespace that groups related types, preventing name clashes and keeping big projects organised. Its name usually matches the source folder structure.

Why this matters

Every real Java project uses packages, and `import java.util.Scanner;` is you using one already.

Real-life analogy

Packages are like subject-wise folders in your bag. Two notebooks can both be called 'Notes' as long as they live in different folders.

Example

Java
// File: college/Student.java
package college;

public class Student {
    public String name = "Ananya Rao";
}

// File: Main.java
import college.Student;

public class Main {
    public static void main(String[] args) {
        Student s = new Student();
        System.out.println(s.name);
    }
}

Output

Ananya Rao

Step by step

  1. 1`package college;` appears before imports and normally matches the source folder structure.
  2. 2The class must be public to be used from outside its package.
  3. 3`import college.Student;` brings that class into another file.
  4. 4`import java.util.*;` imports everything in the java.util package.

Key points

  • package statement comes first, before imports
  • Built-in packages: java.lang (auto-imported), java.util, java.io
  • Packages prevent naming conflicts and control access
  • Folder structure must match the package name

Common mistakes

  • Putting the package statement after an import
  • Package name not matching the directory
  • Forgetting that only public classes are visible across packages

Try it yourself

  • Create a package named shapes containing Circle and Square.
  • List three classes from java.util you have already used.
Open the practice notebook