Creating and Using Packages in Java

In Java, packages are used to organize and group related classes and interfaces. They help in avoiding naming conflicts and provide a way to create a modular and structured codebase.

Creating a Package:

To create a package, include the package statement at the beginning of your Java file. The package name should reflect the directory structure.


// File: MyPackageExample.java
package com.example.mypackage;

public class MyPackageExample {
  public void display() {
    System.out.println("Hello from MyPackageExample!");
  }
}

Using a Package:

To use a class from a package, you can import it at the beginning of your Java file using the import statement.


// File: MyMainClass.java
import com.example.mypackage.MyPackageExample;

public class MyMainClass {
  public static void main(String[] args) {
    MyPackageExample example = new MyPackageExample();
    example.display();
  }
}

Compiling and Running:

When compiling and running Java files in packages, make sure to maintain the directory structure. For example, if the MyPackageExample.java file is in the com/example/mypackage directory, the MyMainClass.java file should be outside this directory.


// Compile and run commands
javac com/example/mypackage/MyPackageExample.java
javac MyMainClass.java
java MyMainClass

Note:

Packages provide a way to organize code and avoid naming conflicts. They are crucial for creating maintainable and modular Java applications. When using packages, be mindful of the directory structure and import classes as needed.