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.
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.Listandjava.awt.Listare 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.
| Kind | Who creates it | Examples |
|---|---|---|
| Built-in packages | Shipped with the JDK | java.lang, java.util, java.io, java.time |
| User-defined packages | You (or your team / library vendor) | com.learncodeguru.bank, com.myshop.order |
| Default (unnamed) package | No package line in the file | Scratch files only; cannot be imported |
Why use packages?
- Avoid name conflicts: two teams can both write a class named
Accountin 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
publicAPI. - 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
| Package | What it contains | Common classes |
|---|---|---|
java.lang | Core language classes (auto-imported) | String, Math, Object, System, Integer, Thread |
java.util | Collections and utilities | ArrayList, HashMap, Scanner, Arrays, Optional |
java.io | Stream-based input and output | File, BufferedReader, FileWriter, Serializable |
java.nio.file | Modern file APIs | Path, Paths, Files |
java.time | Date and time (Java 8+) | LocalDate, LocalDateTime, Duration |
java.util.concurrent | Concurrency utilities | ExecutorService, ConcurrentHashMap, CompletableFuture |
java.util.function | Functional interfaces | Function, Predicate, Supplier, Consumer |
java.sql | JDBC database access | Connection, PreparedStatement, ResultSet |
java.net | Networking | URL, URI, Socket, http.HttpClient (in java.net.http) |
java.text | Formatting | NumberFormat, DecimalFormat, SimpleDateFormat |
javax.swing / java.awt | Desktop GUI | JFrame, JButton, Color |
Package naming conventions
- Use your reversed internet domain as the prefix so names are globally unique:
learncodeguru.combecomescom.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.
| Rule | Good | Bad |
|---|---|---|
| Reverse domain prefix | com.learncodeguru.bank | bank |
| All lowercase | com.myshop.order | com.MyShop.Order |
| No hyphens | com.my_shop.util | com.my-shop.util |
| No keywords | com.app.models | com.app.class |
| Meaningful layers | com.app.service | com.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
packagestatement per file, and at most onepublictop-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
Accountispublic, so other packages can use it.InterestCalchas no modifier, so it is package-private: only classes incom.learncodeguru.bankcan 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 thepackageline and before the class. - You can now use the simple name
Account. Onlypublicclasses andpublicmembers are visible here. - Trying to use
InterestCalcorbranchfromcom.learncodeguru.appis 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 outtellsjavacwhere to put class files; it createsout/com/learncodeguru/...automatically.-cp(classpath) tellsjavawhere 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
| Way | Syntax | What becomes available | When to use |
|---|---|---|---|
| Fully qualified name | java.util.List<String> x; | Nothing imported; full name used each time | One-off use or name conflicts |
| Single-type import | import java.util.ArrayList; | Only ArrayList | Default choice; clearest |
| On-demand (wildcard) import | import java.util.*; | All public types in java.util (not sub-packages) | Many classes from one package |
| Static single import | import static java.lang.Math.sqrt; | Only the static member sqrt | Frequently used constants / helpers |
| Static on-demand import | import static java.lang.Math.*; | All static members of Math | Test code (Assertions.*); use sparingly |
| Automatic import | (nothing written) | All of java.lang and the current package | Always on |
import rules and name conflicts
- File order is fixed: optional
packageline, thenimportlines, then type declarations. import java.util.*;does not importjava.util.functionorjava.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.Dateandjava.sql.Date), import one and fully qualify the other. - A single-type import wins over a wildcard import when both supply the same name.
importis 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).
| Modifier | Same class | Same package (subclass) | Same package (non-subclass) | Other package (subclass) | Other package (non-subclass) |
|---|---|---|---|---|---|
private | Yes | No | No | No | No |
| default (no modifier) | Yes | Yes | Yes | No | No |
protected | Yes | Yes | Yes | Yes (through inheritance only) | No |
public | Yes | Yes | Yes | Yes | Yes |
Access levels on user-defined packages (worked example)
- Using the
Accountclass above (packagecom.learncodeguru.bank), this table shows which member can be reached from each class. Telleris in the same package.SavingsAccount extends Accountis incom.learncodeguru.app.Mainis incom.learncodeguru.appand does not extendAccount.
| Member in Account | Modifier | Inside Account | bank.Teller (same pkg) | app.SavingsAccount (subclass, other pkg) | app.Main (other pkg) |
|---|---|---|---|---|---|
balance | private | Yes | No | No | No |
branch | default | Yes | Yes | No | No |
owner | protected | Yes | Yes | Yes (as this.owner) | No |
deposit(), getBalance() | public | Yes | Yes | Yes | Yes |
class InterestCalc | default class | Yes | Yes | No | No |
// 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
publicor default.privateandprotectedare allowed only on nested (inner) classes. - A file can contain many default classes but at most one
publicclass, and that class must match the file name.
| Top-level class | Visible in same package | Visible in other packages | Can be imported |
|---|---|---|---|
public class Account | Yes | Yes | Yes |
class InterestCalc (default) | Yes | No | No (compile error) |
private class X / protected class X | Not allowed at top level | Not allowed | Not allowed |
Sub-packages are separate packages
com.learncodeguru.bankandcom.learncodeguru.bank.loanslook nested, but Java treats them as two unrelated packages.- Package-private members of
bankare not visible inbank.loans, andimport com.learncodeguru.bank.*;does not importbank.loanstypes. - The dots only describe folder nesting and naming, not access.
Advanced — Packages
The protected rule across packages
- From a subclass in another package, a
protectedmember is accessible only throughthis,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,
protectedbehaves 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 withjava -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
packageline 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
packagestatement, with no class. - Tools use it for things like
@NonNullByDefaultor JAXB@XmlSchemasettings.
// 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 staticfield 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: apublicclass is visible outside the module only if its package is exported.
| Point | Package | Module (Java 9+) |
|---|---|---|
| Groups | Classes and interfaces | Packages |
| Declared by | package statement in each file | module-info.java at the module root |
| Visibility control | public / protected / default / private | exports and requires on top of access modifiers |
| public class visible everywhere? | Yes, on the classpath | Only if its package is exported |
| Dependencies | Implicit through the classpath | Explicit requires clauses |
| Required? | Strongly recommended for all code | Optional; 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;
} 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.
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 Problem Solving Tricks
- Folder path must match the package name exactly:
package a.b.c;lives ina/b/c/. - Always run with dots and the classpath:
java -cp out com.app.Main, neverjava 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.appandcom.app.utilas 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 -dandjava -cpby hand at least once.
Practice Programs List
- Create package
com.learncodeguru.shapeswith public classesCircleandRectangle, and use them fromcom.learncodeguru.app.Main. - Compile the project with
javac -d outand run it withjava -cp outfrom the command line. - Add a package-private helper class
AreaUtilinshapesand confirm it cannot be imported fromapp. - Create
pack1.Basewith one field of each access level and test access frompack1, a subclass inpack2, and a non-subclass inpack2. Record the results in a table. - Show the protected rule: in a subclass in another package, access a protected field through
thisand through a parent-type reference, and read the compiler error. - Use both
java.util.Dateandjava.sql.Datein one class. - Use static imports for
Math.PIandMath.powto compute the area of a circle. - Create
com.appandcom.app.utilwith a package-private method incom.appand provecom.app.utilcannot call it. - Try to import a class from the default package into a named package and note the error.
- Build a layered project with
model,service, andapppackages for a library system (Book, BookService, LibraryApp). - Package your
shapesclasses intoshapes.jarand use them from a separate project via-cp. - Write a
package-info.javawith Javadoc for yourshapespackage. - Create an executable JAR with
jar cfeand run it withjava -jar. - Add a
module-info.javathat exportscom.learncodeguru.shapesbut notcom.learncodeguru.shapes.internal.