Master Core Java Concepts!
Subscribe to Ram N Java for clear explanations, practical code examples, and essential Java tutorials!
Subscribe Now on YouTubeWhat 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
- Declare the Nested Package: Place
package parent.child;as the first line of your Java source file. - Compile with
-d: Runjavac -d . ClassName.javaso the Java compiler automatically creates theparent/childdirectory structure and places the.classfile inside it. - Run with the Full Package Path: Execute the program using
java parent.child.ClassName.
Code Example: Two-Level Package
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.
No comments:
Post a Comment