Wednesday, 2 September 2015

Java Tutorial : Java Package Example (Two Level)

Master Core Java Concepts!

Subscribe to Ram N Java for clear explanations, practical code examples, and essential Java tutorials!

Subscribe Now on YouTube

What Is a Two-Level Package in Java?

A two-level package in Java is a user-defined package that organizes classes into a nested folder hierarchy—one main package folder containing a sub-package folder inside it (for example, package com.ramnjava;).

Using a two-level structure helps you separate modules cleanly, mirror your domain or project structure, and prevent class name conflicts across larger applications.

How to Create and Run a Two-Level Package

  1. Declare the Nested Package: Place package parent.child; as the first line of your Java source file.
  2. Compile with -d: Run javac -d . ClassName.java so the Java compiler automatically creates the parent/child directory structure and places the .class file inside it.
  3. Run with the Full Package Path: Execute the program using java parent.child.ClassName.

Code Example: Two-Level Package

// File: Welcome.java
package com.ramnjava;

public class Welcome {
  public static void main(String[] args) {
    System.out.println("Welcome to a two-level Java package!");
  }
}

// Compile: javac -d . Welcome.java
// Run: java com.ramnjava.Welcome

Key Takeaways

✔️ Dot-Separated Hierarchy: Each dot (.) in a package name represents a nested subfolder on disk.

✔️ Automatic Directory Creation: The -d . flag tells javac to build the nested folders for you.

✔️ Qualified Execution: Always run the compiled class using its full package path.


Watch More Java Tutorials:

No comments:

Post a Comment

Tutorials