Clean • Professional
In Java, packages are used to organize classes and interfaces into separate namespaces.
They help make large projects more manageable, reusable, and prevent class name conflicts.

You must declare the package at the top of your Java file (before imports or class definitions).
// File: mypack/Message.java
package mypack;
public class Message {
public void show() {
System.out.println("Hello from mypack!");
}
}
Note: The folder name must match the package name (mypack).
Use the -d option with the compiler to generate the correct folder structure:
javac -d . Message.java
Explanation:
d . → tells the compiler to place compiled files in a directory structure based on the package.. → current working directory.After compiling, you’ll get this structure:
|-- mypack
|-- Message.class
Now, create another file to use the class from the package.
// File: TestPackage.java
import mypack.Message; // importing class
public class TestPackage {
public static void main(String[] args) {
Message msg = new Message();
msg.show();
}
}
Run it:
java TestPackage
Output:
Hello from mypack!
There are three ways to import classes from a package:

1. Import a Single Class
import mypack.Message;
2. Import All Classes in a Package
import mypack.*;
3. Use Fully Qualified Class Name
public class Main {
public static void main(String[] args) {
mypack.Message msg = new mypack.Message();
msg.show();
}
}
Works without import, but not recommended for large codebases.
package keyword at the top of the file.import to access classes from other packages.javac -d . to maintain proper directory structure.