Packages: Need, Defining a Package, Directory Hierarchy & CLASSPATH
1. Topic Introduction
Imagine two developers in a large project both create a class named Account or Student. Without namespaces, their .class files collide and overwrite each other! Java solves both naming collisions and fine-grained visibility control through Packages, backed by the CLASSPATH mechanism so javac and the JVM always know where to locate packaged .class files and .jar libraries.
Packages) & Giving Java the Map (CLASSPATH)If you drop 500 loose papers onto your desk (default unnamed package), you can't have two files called Notes.pdf and everything becomes chaotic. Instead, you organize folders like Semester3/OOPS/Notes.pdf and Semester4/DBMS/Notes.pdf. In Java, a Package is literally a folder hierarchy (com.ktu.oop), and **CLASSPATH is the list of starting folders** (./classes, ./libs/mysql.jar) where Java searches for those packages!
package pkg1.pkg2; must be the FIRST statement in a .java file, must match an exact case-sensitive folder path (pkg1/pkg2/), and CLASSPATH (or -cp) tells javac/java where the root of that folder tree lives.3. Essential Exam Definitions
package declaration; recommended only for small test programs.-cp / -classpath CLI flag telling javac and the JVM which root directories and .jar/.zip archives to search for user-defined classes and third-party libraries.4. Detailed Technical Explanation & Syntax
1. Need for Packages & Built-in vs User-Defined Packages
Why packages exist: (1) Avoid name clashes (java.util.Date vs java.sql.Date coexist cleanly); (2) Logical modular organization; (3) Access protection (default and protected visibility boundaries rely on packages).
Built-in Packages include java.lang (core String, Math, System—auto-imported), java.util (Vector, Scanner, ArrayList), java.io, java.awt, javax.swing, and java.sql. User-defined packages are created by programmers using package.
2. Defining a Package & Directory Mapping Rules
Place package pkg1[.pkg2[.pkg3]]; as the very first non-comment statement in the .java file.
Directory Mapping Law: Java maps package names directly to OS directories. Case is strictly significant! For example, package mypack; requires AccountBalance.class to reside inside mypack/AccountBalance.class; package com.ktu.oop; requires com/ktu/oop/. You CANNOT rename a package without moving/renaming its matching directories.
Compiling with -d: Running javac -d ./classes MyClass.java instructs javac to automatically create the nested package directories inside ./classes!
3. Finding Packages & Setting CLASSPATH
Java locates packages in three ways: (1) Current working directory (., default when no classpath overrides it); (2) Setting the OS CLASSPATH environment variable; (3) Passing -classpath or -cp to javac and java (recommended because it overrides global settings per execution).
CRITICAL RULE from your notes: The CLASSPATH entry MUST point to the **directory ABOVE MyPack** (the root), NOT inside MyPack/ itself! Also remember OS separators: Linux/macOS uses colon :, while Windows uses semicolon ;.
5. Working Principle: Compiling & Running a Packaged Class from the Root Directory
- 1. Write
AccountBalance.javastarting withpackage mypack;. - 2. Compile from root with destination flag:
javac -d . AccountBalance.java(creates./mypack/AccountBalance.class). - 3. Run from the root directory (ABOVE
mypack/) using the fully qualified name:java mypack.AccountBalance(orjava -cp .:./libs/* mypack.AccountBalance).
6. Examination-Ready Diagrams
Package Directory Structure & Access Scope
Illustrates how Java maps dot-separated hierarchical package names (com.ktu.oop) directly to nested OS file system directories and how CLASSPATH locates root packages.
- CLASSPATH Root: Directory (
./classesor.) from which JVM/javac begins package lookup. - Subdirectories (
com/ktu/oop): Each dot segment corresponds to an exact case-sensitive folder. - Compiled
.classFiles: Stored inside the leaf package directory (Student.class,Course.class).
- Source file declares
package com.ktu.oop;as its very first non-comment statement. - Compiled via
javac -d ./classes Student.java, which auto-createsclasses/com/ktu/oop/Student.class. - Executed via
java -cp ./classes com.ktu.oop.Studentfrom any working folder.
- Draw a tree structure starting from
CLASSPATH Root (e.g., project/classes)->p1/(Protection.class,Derived.class,SamePackage.class) andp2/(Protection2.class,OtherPackage.class). - Annotate the 4 visibility boundaries: Same Class, Same Package, Subclass in Different Package, Non-subclass in Different Package.
7. Complete Java Code Examples & Tracing
mypack containing a Balance helper and public AccountBalance driver class. Must be compiled with javac -d . AccountBalance.java and run with java mypack.AccountBalance.| 1 | package mypack; |
| 2 | |
| 3 | class Balance { |
| 4 | String name; |
| 5 | double bal; |
| 6 | |
| 7 | Balance(String n, double b) { |
| 8 | name = n; |
| 9 | bal = b; |
| 10 | } |
| 11 | |
| 12 | void show() { |
| 13 | if (bal < 0) { |
| 14 | System.out.print("--> "); |
| 15 | } |
| 16 | System.out.println(name + ": Rs." + bal); |
| 17 | } |
| 18 | } |
| 19 | |
| 20 | public class AccountBalance { |
| 21 | public static void main(String[] args) { |
| 22 | Balance[] current = new Balance[3]; |
| 23 | current[0] = new Balance("K. J. Fielding", 123.23); |
| 24 | current[1] = new Balance("Will Tell", 157.02); |
| 25 | current[2] = new Balance("Tom Jackson", -12.33); |
| 26 | |
| 27 | for (Balance b : current) { |
| 28 | b.show(); |
| 29 | } |
| 30 | } |
| 31 | } |
K. J. Fielding: Rs.123.23 Will Tell: Rs.157.02 --> Tom Jackson: Rs.-12.33
packagepublicclass- Placing
importstatements BEFOREpackage mypack;(packageMUST come first!). - Running
cd mypack && java AccountBalance— throwsNoClassDefFoundErrorbecause you must runjava mypack.AccountBalancefrom the parent directory! - Including the package folder name inside
CLASSPATHitself.
Real-World Applications
- Every large Java library uses reverse-domain package hierarchy (
org.apache.*,javax.swing.*,java.sql.*) to eliminate class name collisions worldwide.
Important KTU Exam Points
- Mention BOTH roles of packages: Naming mechanism (collision prevention) + Visibility control mechanism.
- Highlight the exact
CLASSPATHrule: point to the root folder ABOVE the package directory, and distinguish-cp(:on Linux/macOS vs;on Windows).
Memory Techniques & Revision
- File Top Order — 'P-I-C':
packagefirst,importsecond,classthird!
Common Pitfalls to Avoid
- Confusing
package(declaring which package the current file belongs to) withimport(bringing external packages into visibility).
KTU-Style Questions & Exam-Ready Answers
Structured specifically for KTU Part A (3-mark) and Part B (6/9-mark) evaluation rubrics.
Introduction: A package is a hierarchical container of classes and interfaces that acts as both a namespace (preventing name collisions) and an access-control boundary.
- Creating a Package: Place
package pkgName;as the very first statement in.java, store/compile.classinside a directory matchingpkgName(javac -d . File.java), and execute withjava pkgName.ClassNamefrom the parent folder. - CLASSPATH: Environment variable or
-cpcommand-line flag specifying root directories and.jararchives wherejavacand JVM search for user classes and packages (using:on Linux/macOS,;on Windows; default.).
p1/ and p2/ folders.Quick Understanding Check
1. If Student.java begins with package com.ktu;, from where should you run java com.ktu.Student?