Java Program to demonstrate packages
Program
package demopack;
public class PackageDemo
{
public static void main(String[] args)
{
System.out.println("Welcome to oodlescoop");
System.out.println("This is package demo");
}
}
This program demonstrates the use of packages in Java.
What are Packages?
- Packages are a way to organize Java classes into namespaces or directories.
- They help group related classes together, prevent naming conflicts, and make code modular and easier to maintain.
- A package can be explicitly declared at the beginning of a Java file using the
package
keyword.
-
Package Declaration:
- The line
package demopack;
specifies that this class belongs to the package nameddemopack
. - It must be the first statement (excluding comments) in the Java file.
- The line
-
Class
PackageDemo
:- Contains the
main()
method, which is the entry point of the program. - Prints two lines to the console:
"Welcome to oodlescoop"
"This is package demo"
- Contains the
-
Compilation and Execution:
- When using packages, the Java file must be saved in a folder matching the package name (
demopack
in this case). - The program should be compiled and executed as follows:
- Save the file as
PackageDemo.java
inside a folder nameddemopack
. - Navigate to the parent directory of
demopack
in the terminal or command prompt. - Compile using:
javac demopack/PackageDemo.java
- Run the program using:
java demopack.PackageDemo
- Save the file as
- When using packages, the Java file must be saved in a folder matching the package name (
Key Points:
-
Purpose of Packages:
- Packages are used to avoid naming conflicts (e.g., multiple classes with the same name in different packages).
- They enable easier code organization, especially for large applications.
-
Structure:
- The directory structure must match the package name.
- For the package
demopack
, the file must reside in a folder nameddemopack
.
-
Package Naming Convention:
- Packages are usually named using lowercase letters.
- To make package names unique in large projects, they often follow reverse domain name conventions (e.g.,
com.example.myapp
).
-
Accessing Classes in a Package:
- Classes from a package can be accessed by importing the package using the
import
keyword or by specifying the fully qualified name of the class.
- Classes from a package can be accessed by importing the package using the
Output
$ javac -d . PackageDemo.java
$ java demopack.PackageDemo
Welcome to oodlescoop
This is package demo