Skip to main content

Language Features

Packages

Complete lesson for Packages using LEARNCODEGURU’s 6-level learning model — from basics to advanced practice, with Java OOP and Collections where relevant.

L1

Basics — Packages

Section: Language Features. Java packages — built-in and user-defined packages, how to create and compile them, every way to import, access levels across packages, classpath, JAR files, and modules.

What is a package?

  • A package is a named group of related classes, interfaces, enums, and records. It works like a folder for Java types.
  • It gives every type a unique full name: java.util.List and java.awt.List are two different classes.
  • The package also forms an access boundary: members with no modifier (package-private) are visible only inside the same package.
  • Real-life analogy: a city has many people named Ravi, but "Ravi, 12 MG Road, Bengaluru" is unique. The package is the address.
KindWho creates itExamples
Built-in packagesShipped with the JDKjava.lang, java.util, java.io, java.time
User-defined packagesYou (or your team / library vendor)com.learncodeguru.bank, com.myshop.order
Default (unnamed) packageNo package line in the fileScratch files only; cannot be imported

Why use packages?

  • Avoid name conflicts: two teams can both write a class named Account in different packages.
  • Organize large projects by feature or layer (model, service, controller, util).
  • Control access: hide helper classes with package-private visibility and expose only a small public API.
  • Reuse: package code into a JAR and import it in other projects.
  • Easier searching and maintenance: the folder tree mirrors the package tree.

Common built-in packages

PackageWhat it containsCommon classes
java.langCore language classes (auto-imported)String, Math, Object, System, Integer, Thread
java.utilCollections and utilitiesArrayList, HashMap, Scanner, Arrays, Optional
java.ioStream-based input and outputFile, BufferedReader, FileWriter, Serializable
java.nio.fileModern file APIsPath, Paths, Files
java.timeDate and time (Java 8+)LocalDate, LocalDateTime, Duration
java.util.concurrentConcurrency utilitiesExecutorService, ConcurrentHashMap, CompletableFuture
java.util.functionFunctional interfacesFunction, Predicate, Supplier, Consumer
java.sqlJDBC database accessConnection, PreparedStatement, ResultSet
java.netNetworkingURL, URI, Socket, http.HttpClient (in java.net.http)
java.textFormattingNumberFormat, DecimalFormat, SimpleDateFormat
javax.swing / java.awtDesktop GUIJFrame, JButton, Color

Package naming conventions

  • Use your reversed internet domain as the prefix so names are globally unique: learncodeguru.com becomes com.learncodeguru.
  • Use all lowercase letters. Separate levels with dots.
  • A hyphen or a Java keyword is not allowed in a package name: use com.learncodeguru.int_ or rename it.
RuleGoodBad
Reverse domain prefixcom.learncodeguru.bankbank
All lowercasecom.myshop.ordercom.MyShop.Order
No hyphenscom.my_shop.utilcom.my-shop.util
No keywordscom.app.modelscom.app.class
Meaningful layerscom.app.servicecom.app.stuff

How to create a user-defined package (step by step)

  • Step 1: Choose a package name, for example com.learncodeguru.bank.
  • Step 2: Create matching folders under a source root: src/com/learncodeguru/bank/.
  • Step 3: Write package com.learncodeguru.bank; as the first statement of every file in that folder (only comments may come before it).
  • Step 4: Mark the classes and members that other packages need as public.
  • Step 5: Compile with javac -d out ... so the compiler creates the package folders for the class files.
  • Step 6: Run with the fully qualified name: java -cp out com.learncodeguru.app.Main.
  • Rule: one package statement per file, and at most one public top-level class per file, named exactly like the file.
project/
 └── src/
      └── com/
           └── learncodeguru/
                ├── bank/
                │    ├── Account.java(package com.learncodeguru.bank;)
                │    └── InterestCalc.java(package com.learncodeguru.bank;)
                └── app/
                     └── Main.java(package com.learncodeguru.app;)

Writing classes inside the user-defined package

  • Account is public, so other packages can use it.
  • InterestCalc has no modifier, so it is package-private: only classes in com.learncodeguru.bank can use it.
  • This is the usual design: a small public API plus hidden helper classes.
// File: src/com/learncodeguru/bank/Account.java
package com.learncodeguru.bank;

public class Account {
    private double balance;                 // only inside Account
    protected String owner;                 // same package + subclasses
    String branch = "Hyderabad";            // package-private

    public Account(String owner, double opening) {
        this.owner = owner;
        this.balance = opening;
    }

    public void deposit(double amt) {
        if (amt <= 0) throw new IllegalArgumentException("amount must be > 0");
        balance += amt;
    }

    public double getBalance() { return balance; }

    public double yearlyInterest() {
        return InterestCalc.interest(balance);   // same package: allowed
    }
}

// File: src/com/learncodeguru/bank/InterestCalc.java
package com.learncodeguru.bank;

class InterestCalc {                        // package-private class
    static double interest(double amount) {
        return amount * 0.04;
    }
}

Importing the user-defined package

  • In another package, write import com.learncodeguru.bank.Account; after the package line and before the class.
  • You can now use the simple name Account. Only public classes and public members are visible here.
  • Trying to use InterestCalc or branch from com.learncodeguru.app is a compile-time error.
// File: src/com/learncodeguru/app/Main.java
package com.learncodeguru.app;

import com.learncodeguru.bank.Account;      // single-type import

public class Main {
    public static void main(String[] args) {
        Account acc = new Account("Ravi", 1000);
        acc.deposit(500);
        System.out.println(acc.getBalance());     // 1500.0
        System.out.println(acc.yearlyInterest()); // 60.0

        // acc.balance;        error: balance has private access
        // acc.branch;         error: branch is not public; cannot be accessed from outside package
        // acc.owner;          error: owner has protected access (Main is not a subclass)
        // new InterestCalc(); error: InterestCalc is not public
    }
}

Compiling and running packaged classes

  • Run the commands from the project folder (the parent of src).
  • -d out tells javac where to put class files; it creates out/com/learncodeguru/... automatically.
  • -cp (classpath) tells java where the package root is. Separate multiple entries with ; on Windows and : on Linux / macOS.
  • Always run with the fully qualified class name, never with a file path.
# compile every file in both packages
javac -d out src/com/learncodeguru/bank/*.java src/com/learncodeguru/app/Main.java

# resulting layout
# out/com/learncodeguru/bank/Account.class
# out/com/learncodeguru/bank/InterestCalc.class
# out/com/learncodeguru/app/Main.class

# run with the fully qualified name
java -cp out com.learncodeguru.app.Main

# common mistakes
# java Main                         -> Error: Could not find or load main class Main
# java out/com/learncodeguru/app/Main -> wrong: use dots and -cp, not a path

Ways to import and use classes from another package

WaySyntaxWhat becomes availableWhen to use
Fully qualified namejava.util.List<String> x;Nothing imported; full name used each timeOne-off use or name conflicts
Single-type importimport java.util.ArrayList;Only ArrayListDefault choice; clearest
On-demand (wildcard) importimport java.util.*;All public types in java.util (not sub-packages)Many classes from one package
Static single importimport static java.lang.Math.sqrt;Only the static member sqrtFrequently used constants / helpers
Static on-demand importimport static java.lang.Math.*;All static members of MathTest code (Assertions.*); use sparingly
Automatic import(nothing written)All of java.lang and the current packageAlways on

import rules and name conflicts

  • File order is fixed: optional package line, then import lines, then type declarations.
  • import java.util.*; does not import java.util.function or java.util.concurrent. Each sub-package is a separate package.
  • Classes in the same package never need an import.
  • If two imports provide the same simple name (java.util.Date and java.sql.Date), import one and fully qualify the other.
  • A single-type import wins over a wildcard import when both supply the same name.
  • import is compile-time only: it does not load classes, copy code, or slow down the program.
package com.learncodeguru.app;

import java.util.Date;                       // java.util.Date gets the simple name

public class DateConflict {
    public static void main(String[] args) {
        Date now = new Date();
        java.sql.Date sqlDate = java.sql.Date.valueOf("2026-10-08"); // fully qualified
        System.out.println(now);
        System.out.println(sqlDate);
    }
}

Access levels across packages

  • Java has four access levels. Three use keywords; the fourth (default, also called package-private) is written as no modifier at all.
  • The table reads from the most restrictive (private) to the most open (public).
ModifierSame classSame package (subclass)Same package (non-subclass)Other package (subclass)Other package (non-subclass)
privateYesNoNoNoNo
default (no modifier)YesYesYesNoNo
protectedYesYesYesYes (through inheritance only)No
publicYesYesYesYesYes

Access levels on user-defined packages (worked example)

  • Using the Account class above (package com.learncodeguru.bank), this table shows which member can be reached from each class.
  • Teller is in the same package. SavingsAccount extends Account is in com.learncodeguru.app. Main is in com.learncodeguru.app and does not extend Account.
Member in AccountModifierInside Accountbank.Teller (same pkg)app.SavingsAccount (subclass, other pkg)app.Main (other pkg)
balanceprivateYesNoNoNo
branchdefaultYesYesNoNo
ownerprotectedYesYesYes (as this.owner)No
deposit(), getBalance()publicYesYesYesYes
class InterestCalcdefault classYesYesNoNo
// File: src/com/learncodeguru/bank/Teller.java  (same package)
package com.learncodeguru.bank;

public class Teller {
    public static void audit(Account a) {
        System.out.println(a.owner);        // OK: protected is visible in same package
        System.out.println(a.branch);       // OK: default is visible in same package
        // System.out.println(a.balance);   // error: private
    }
}

// File: src/com/learncodeguru/app/SavingsAccount.java  (subclass, other package)
package com.learncodeguru.app;

import com.learncodeguru.bank.Account;

public class SavingsAccount extends Account {
    public SavingsAccount(String owner, double opening) {
        super(owner, opening);
    }

    public String label() {
        return "Savings of " + owner;         // OK: protected via inheritance
        // return branch;                      // error: default not visible outside bank
    }
}

Class-level access: public class vs default class

  • A top-level class can only be public or default. private and protected are allowed only on nested (inner) classes.
  • A file can contain many default classes but at most one public class, and that class must match the file name.
Top-level classVisible in same packageVisible in other packagesCan be imported
public class AccountYesYesYes
class InterestCalc (default)YesNoNo (compile error)
private class X / protected class XNot allowed at top levelNot allowedNot allowed

Sub-packages are separate packages

  • com.learncodeguru.bank and com.learncodeguru.bank.loans look nested, but Java treats them as two unrelated packages.
  • Package-private members of bank are not visible in bank.loans, and import com.learncodeguru.bank.*; does not import bank.loans types.
  • The dots only describe folder nesting and naming, not access.
L2

Advanced — Packages

The protected rule across packages

  • From a subclass in another package, a protected member is accessible only through this, super, or a reference of the subclass type (or its own subclasses).
  • Accessing it through a plain parent reference (Account a = ...; a.owner) from the other package is a compile error, even inside the subclass.
  • Within the same package, protected behaves exactly like default access plus inheritance.
package com.learncodeguru.app;

import com.learncodeguru.bank.Account;

public class SavingsAccount extends Account {
    public SavingsAccount(String owner, double opening) { super(owner, opening); }

    void demo(Account other, SavingsAccount same) {
        System.out.println(this.owner);    // OK
        System.out.println(same.owner);    // OK: reference is SavingsAccount
        // System.out.println(other.owner); // error: owner has protected access in Account
    }
}

Classpath, JAR files, and reusing your package

  • The classpath is the list of folders and JAR files the JVM searches for classes, starting from each package root.
  • Package your compiled classes into a JAR to share them: other projects add the JAR to their classpath and import your packages.
  • An executable JAR records the main class in its manifest (-e / cfe), so you can run it with java -jar.
  • Build tools (Maven, Gradle) and IDEs manage the classpath for you, but the rules are the same.
# build a library JAR from the compiled bank package
jar cf bank.jar -C out com/learncodeguru/bank

# build an executable JAR with Main as the entry point
jar cfe app.jar com.learncodeguru.app.Main -C out .
java -jar app.jar

# use bank.jar from another project
javac -cp bank.jar -d out2 src/com/other/Client.java
java -cp "out2;bank.jar" com.other.Client     # Windows(use : on Linux/macOS)

Default (unnamed) package limitations

  • A class with no package line lives in the unnamed package.
  • Classes in named packages cannot import classes from the unnamed package at all. There is no syntax for it.
  • It is fine for one-file experiments, but real projects should always declare a package.

package-info.java

  • A special file in the package folder that holds package-level Javadoc and annotations.
  • It contains only comments, annotations, and the package statement, with no class.
  • Tools use it for things like @NonNullByDefault or JAXB @XmlSchema settings.
// File: src/com/learncodeguru/bank/package-info.java
/**
 * Core banking types: accounts, deposits, and interest.
 * Only Account is public; helpers stay package-private.
 */
package com.learncodeguru.bank;

Static import: power and pitfalls

  • Static import works on any public static field or method, including your own: import static com.learncodeguru.bank.Rates.GST;.
  • Overusing import static ...* hides where a name comes from. Keep it for constants and test assertions.
  • If a static import and a local member share a name, the local member wins.
import static java.lang.Math.PI;
import static java.lang.Math.pow;

public class Circle {
    public static void main(String[] args) {
        double r = 2.5;
        System.out.println(PI * pow(r, 2)); // 19.634954084936208
    }
}

Differences between packages and modules

  • Java 9 modules (module-info.java) group packages and add a stronger boundary: a public class is visible outside the module only if its package is exported.
PointPackageModule (Java 9+)
GroupsClasses and interfacesPackages
Declared bypackage statement in each filemodule-info.java at the module root
Visibility controlpublic / protected / default / privateexports and requires on top of access modifiers
public class visible everywhere?Yes, on the classpathOnly if its package is exported
DependenciesImplicit through the classpathExplicit requires clauses
Required?Strongly recommended for all codeOptional; classpath apps still work
// File: src/module-info.java
module com.learncodeguru.bankapp {
    exports com.learncodeguru.bank;        // visible to other modules
    // com.learncodeguru.bank.internal stays hidden even if its classes are public
    requires java.sql;
}
L3

Tricky Interview Points

Q1) What is a package in Java?

Answer A namespace that groups related types, maps to a folder structure, prevents name conflicts, and defines the package-private access boundary.

Q2) What are the types of packages?

Answer Built-in packages from the JDK (java.lang, java.util, java.io, ...) and user-defined packages that you create with the package statement.

Q3) How do you create a user-defined package?

Answer Write package com.example.util; as the first statement, place the file in the matching folder com/example/util, compile with javac -d out, and run with java -cp out followed by the fully qualified class name.

Q4) Where must the package statement appear?

Answer As the first statement in the file (only comments may come before it). Only one package statement is allowed per file.

Q5) Which package is imported automatically?

Answer java.lang, plus the current package. Sub-packages such as java.lang.reflect still need an import.

Q6) Does import java.util.* import java.util.concurrent?

Answer No. A wildcard imports only the public types of that one package, not its sub-packages.

Q7) Single-type import vs wildcard import: which is faster?

Answer Neither affects runtime. Imports are compile-time name lookups only. Single-type imports are preferred for clarity and to avoid ambiguity.

Q8) What is a static import?

Answer import static brings static members into scope so you can use them without the class name, for example import static java.lang.Math.sqrt; then sqrt(16).

Q9) How do you use two classes with the same name from different packages?

Answer Import one of them and refer to the other by its fully qualified name, for example java.util.Date and java.sql.Date.

Q10) What is the default access modifier and its scope?

Answer No modifier means package-private: visible to every class in the same package and hidden from all other packages, including subclasses there.

Q11) Explain all four access levels across packages.

Answer private: same class only. default: same package only. protected: same package plus subclasses in other packages through inheritance. public: everywhere.

Q12) Can a top-level class be private or protected?

Answer No. A top-level class can only be public or default. private and protected apply to members and nested classes.

Q13) Can a subclass in another package access a protected member through a parent reference?

Answer No. Outside the package it must use this, super, or a reference of the subclass type. Using a plain parent-type reference is a compile error.

Q14) Is com.app.util a part of com.app for access purposes?

Answer No. Sub-packages are completely separate packages. Package-private members of com.app are not visible in com.app.util.

Q15) Can you import a class from the default package?

Answer No. Classes in named packages cannot refer to classes in the unnamed package. Always put real code in a named package.

Q16) What is the classpath?

Answer The list of directories and JAR files the JVM and javac search for classes, each acting as a package root. Set it with -cp or the CLASSPATH variable.

Q17) Package vs module?

Answer A package groups classes; a module (Java 9+) groups packages and controls which packages are exported and which modules are required.

L4

Simple Programs

User-defined package: calculator library and client

// File: src/com/learncodeguru/mathlib/Calculator.java
package com.learncodeguru.mathlib;

public class Calculator {
    public static int add(int a, int b) { return a + b; }
    public static int multiply(int a, int b) { return a * b; }
    public static double average(int... nums) {
        if (nums.length == 0) throw new IllegalArgumentException("no numbers");
        int sum = 0;
        for (int n : nums) sum += n;
        return (double) sum / nums.length;
    }
}

// File: src/com/learncodeguru/app/CalcApp.java
package com.learncodeguru.app;

import com.learncodeguru.mathlib.Calculator;

public class CalcApp {
    public static void main(String[] args) {
        System.out.println(Calculator.add(7, 5));           // 12
        System.out.println(Calculator.multiply(7, 5));      // 35
        System.out.println(Calculator.average(4, 8, 15));   // 9.0
    }
}

// Compile and run from the project folder:
// javac -d out src/com/learncodeguru/mathlib/Calculator.java src/com/learncodeguru/app/CalcApp.java
// java -cp out com.learncodeguru.app.CalcApp

Access modifiers across two packages

// File: src/pack1/Base.java
package pack1;

public class Base {
    private   int a = 1;
    int           b = 2;    // default
    protected int c = 3;
    public    int d = 4;

    public void showAll() {
        System.out.println(a + " " + b + " " + c + " " + d);   // all OK inside Base
    }
}

// File: src/pack1/SamePackage.java
package pack1;

public class SamePackage {
    public static void main(String[] args) {
        Base x = new Base();
        // System.out.println(x.a);  // error: private
        System.out.println(x.b);     // OK: same package
        System.out.println(x.c);     // OK: same package
        System.out.println(x.d);     // OK: public
    }
}

// File: src/pack2/Child.java
package pack2;

import pack1.Base;

public class Child extends Base {
    public void test() {
        // System.out.println(a);    // error: private
        // System.out.println(b);    // error: default, other package
        System.out.println(c);       // OK: protected via inheritance
        System.out.println(d);       // OK: public
    }

    public static void main(String[] args) {
        new Child().test();
    }
}

// File: src/pack2/Stranger.java
package pack2;

import pack1.Base;

public class Stranger {
    public static void main(String[] args) {
        Base x = new Base();
        // System.out.println(x.b);  // error: default
        // System.out.println(x.c);  // error: protected, not a subclass
        System.out.println(x.d);     // OK: public only
    }
}

Wildcard, single-type, and static imports together

package com.learncodeguru.app;

import java.util.*;                       // wildcard: List, ArrayList, Collections ...
import java.time.LocalDate;               // single-type
import static java.lang.Math.max;         // static single
import static java.util.stream.Collectors.joining;

public class ImportsDemo {
    public static void main(String[] args) {
        List<String> langs = new ArrayList<>(List.of("Java", "C", "Python"));
        Collections.sort(langs);
        System.out.println(langs.stream().collect(joining(", "))); // C, Java, Python
        System.out.println(max(10, 42));                           // 42
        System.out.println(LocalDate.of(2026, 10, 8).getDayOfWeek()); // THURSDAY
    }
}

Same class name in two packages

// File: src/com/shop/model/Product.java
package com.shop.model;

public class Product {
    public String name = "Laptop";
}

// File: src/com/shop/legacy/Product.java
package com.shop.legacy;

public class Product {
    public String title = "Old Laptop";
}

// File: src/com/shop/app/Main.java
package com.shop.app;

import com.shop.model.Product;            // gets the simple name

public class Main {
    public static void main(String[] args) {
        Product p = new Product();
        com.shop.legacy.Product old = new com.shop.legacy.Product(); // fully qualified
        System.out.println(p.name + " / " + old.title);
    }
}

Layered project packages (model, service, app)

// File: src/com/learncodeguru/school/model/Student.java
package com.learncodeguru.school.model;

public record Student(int id, String name, double marks) { }

// File: src/com/learncodeguru/school/service/StudentService.java
package com.learncodeguru.school.service;

import com.learncodeguru.school.model.Student;
import java.util.ArrayList;
import java.util.List;

public class StudentService {
    private final List<Student> students = new ArrayList<>();

    public void add(Student s) { students.add(s); }

    public double classAverage() {
        return students.stream().mapToDouble(Student::marks).average().orElse(0);
    }
}

// File: src/com/learncodeguru/school/app/SchoolApp.java
package com.learncodeguru.school.app;

import com.learncodeguru.school.model.Student;
import com.learncodeguru.school.service.StudentService;

public class SchoolApp {
    public static void main(String[] args) {
        StudentService svc = new StudentService();
        svc.add(new Student(1, "Asha", 88));
        svc.add(new Student(2, "Kiran", 74));
        System.out.println("Average = " + svc.classAverage()); // 81.0
    }
}

Build and run script for a packaged project

# 1. compile all sources into out/ (PowerShell)
javac -d out(Get-ChildItem -Recurse src -Filter *.java).FullName

#    Linux / macOS / Git Bash
# javac -d out $(find src -name "*.java")

# 2. run the main class by its fully qualified name
java -cp out com.learncodeguru.school.app.SchoolApp

# 3. package as an executable JAR and run it
jar cfe school.jar com.learncodeguru.school.app.SchoolApp -C out .
java -jar school.jar
L5

Problem Solving Tricks

  • Folder path must match the package name exactly: package a.b.c; lives in a/b/c/.
  • Always run with dots and the classpath: java -cp out com.app.Main, never java out/com/app/Main.
  • Remember the access order from tight to open: private, default, protected, public.
  • Default access stops at the package wall; protected crosses it only through inheritance.
  • Sub-packages are not "inside" their parent for access. Treat com.app and com.app.util as strangers.
  • Prefer single-type imports so readers see where each class comes from; let the IDE organize them.
  • Keep helper classes package-private and expose a small public API.
  • Never ship code in the default package; it cannot be imported.
  • Use ; between classpath entries on Windows and : on Linux / macOS.
  • IDE run buttons hide classpath mistakes. Practice javac -d and java -cp by hand at least once.
L6

Practice Programs List

  1. Create package com.learncodeguru.shapes with public classes Circle and Rectangle, and use them from com.learncodeguru.app.Main.
  2. Compile the project with javac -d out and run it with java -cp out from the command line.
  3. Add a package-private helper class AreaUtil in shapes and confirm it cannot be imported from app.
  4. Create pack1.Base with one field of each access level and test access from pack1, a subclass in pack2, and a non-subclass in pack2. Record the results in a table.
  5. Show the protected rule: in a subclass in another package, access a protected field through this and through a parent-type reference, and read the compiler error.
  6. Use both java.util.Date and java.sql.Date in one class.
  7. Use static imports for Math.PI and Math.pow to compute the area of a circle.
  8. Create com.app and com.app.util with a package-private method in com.app and prove com.app.util cannot call it.
  9. Try to import a class from the default package into a named package and note the error.
  10. Build a layered project with model, service, and app packages for a library system (Book, BookService, LibraryApp).
  11. Package your shapes classes into shapes.jar and use them from a separate project via -cp.
  12. Write a package-info.java with Javadoc for your shapes package.
  13. Create an executable JAR with jar cfe and run it with java -jar.
  14. Add a module-info.java that exports com.learncodeguru.shapes but not com.learncodeguru.shapes.internal.