KTU OOP Java2024 Scheme • 60M ESE
MODULE 3/Section 1: Packages

Packages: Need, Defining a Package, Directory Hierarchy & CLASSPATH

HIGH PRIORITY (Prep Guide)Official Syllabus~15 min study
Official KTU 2024 Syllabus Topics Covered Here
Introduction to packagesNeed for packagesBuilt-in and user-defined packagesDefining a packagePackage declarationCLASSPATH concept

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.

2. Start From Zero: Organizing Files into Folders (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!

Key Takeaway: 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
A namespace container for grouping related classes, interfaces, and sub-packages hierarchically, serving as both a naming mechanism (preventing collisions) and a visibility-control mechanism.
Default (Unnamed) Package
The anonymous package assigned automatically when a Java source file omits the package declaration; recommended only for small test programs.
CLASSPATH
An OS environment variable or -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. 1. Write AccountBalance.java starting with package mypack;.
  2. 2. Compile from root with destination flag: javac -d . AccountBalance.java (creates ./mypack/AccountBalance.class).
  3. 3. Run from the root directory (ABOVE mypack/) using the fully qualified name: java mypack.AccountBalance (or java -cp .:./libs/* mypack.AccountBalance).

6. Examination-Ready Diagrams

Diagram 8

Package Directory Structure & Access Scope

CLASSPATH Root (./classes)java -cp ./classes p1.Derivedpackage p1/ (Folder)Same-package default + protected visiblepackage p2/ (Folder)Needs import p1.*; only public/protectedProtection.classbase classDerived.classextends ProtectionProtection2.classsubclass in p2OtherPkg.classnon-subclass in p2

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.

Key Components
  • CLASSPATH Root: Directory (./classes or .) from which JVM/javac begins package lookup.
  • Subdirectories (com/ktu/oop): Each dot segment corresponds to an exact case-sensitive folder.
  • Compiled .class Files: Stored inside the leaf package directory (Student.class, Course.class).
Step-by-Step Flow
  1. Source file declares package com.ktu.oop; as its very first non-comment statement.
  2. Compiled via javac -d ./classes Student.java, which auto-creates classes/com/ktu/oop/Student.class.
  3. Executed via java -cp ./classes com.ktu.oop.Student from any working folder.
How to Draw in KTU Exam
  • Draw a tree structure starting from CLASSPATH Root (e.g., project/classes) -> p1/ (Protection.class, Derived.class, SamePackage.class) and p2/ (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

User-Defined Package (`mypack`) Creation & ExecutionAccountBalance.java
Declares a user-defined package mypack containing a Balance helper and public AccountBalance driver class. Must be compiled with javac -d . AccountBalance.java and run with java mypack.AccountBalance.
1package mypack;
2
3class 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
20public 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}
Expected Output
K. J. Fielding: Rs.123.23
Will Tell: Rs.157.02
--> Tom Jackson: Rs.-12.33
Keywords:packagepublicclass
Common Exam & Coding Mistakes
  • Placing import statements BEFORE package mypack; (package MUST come first!).
  • Running cd mypack && java AccountBalance — throws NoClassDefFoundError because you must run java mypack.AccountBalance from the parent directory!
  • Including the package folder name inside CLASSPATH itself.

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 CLASSPATH rule: 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': package first, import second, class third!

Common Pitfalls to Avoid

  • Confusing package (declaring which package the current file belongs to) with import (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 .class inside a directory matching pkgName (javac -d . File.java), and execute with java pkgName.ClassName from the parent folder.
  • CLASSPATH: Environment variable or -cp command-line flag specifying root directories and .jar archives where javac and JVM search for user classes and packages (using : on Linux/macOS, ; on Windows; default .).
Exam Diagram Note: Draw Diagram 8 showing CLASSPATH root above 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?