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.
  1. Package Declaration:

    • The line package demopack; specifies that this class belongs to the package named demopack.
    • It must be the first statement (excluding comments) in the Java file.
  2. 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"
  3. 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 named demopack.
      • 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
        

Key Points:

  1. 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.
  2. Structure:

    • The directory structure must match the package name.
    • For the package demopack, the file must reside in a folder named demopack.
  3. 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).
  4. 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.

Output

$ javac -d . PackageDemo.java 
$ java demopack.PackageDemo 
Welcome to oodlescoop
This is package demo