How to Compile Packages in Java

When a Java class is stored in a package, you must include the path that corresponds to the package in the compile. To learn how to compile a Java class in a package and successfully run a Java program to test your work, follow these nine steps.

  1. Create a new folder called compile-packages-in-java.

  2. Create a subfolder in your new folder called personpackage.

  3. Open your text editor and create a new file that will contain the Person class in the personpackage. Be sure to create this file in the personpackage folder. Type in the following Java statements:
    Java Source for Compile Packages Person
    Note the package statement; this statement tells the compiler that the class is contained within the package (i.e., folder) named personpackage. Therefore, the actual name of your Java class is personpackage.Person.

  4. Save your file as

  5. In your text editor, create the Java program that will test the Person class. Be sure to save this file in the compile-packages-in-java folder. Type in the following Java statements:
    Java Source for Compile Packages Tester
    The import statement directs the compiler to resolve references to Person from the personpackage package.

  6. Save your file as

  7. Open a command prompt and navigate to the compile-packages-in-java directory. Then type in the command to compile the Person source and hit Enter. Notice that you provided the path of the Java file. This path corresponds to the package name.
    Compile Compile Packages Person

  8. In the same directory, type in the command to compile the tester class and hit Enter.
    Compile Compile Packages

  9. You are ready test your Person class that is stored in personpackage. Type in the command to run the Java runtime launcher and hit Enter. Observe the output showing the Person you instantiated using personpackage.Person.
    Run Compile Packages
Author: Stephen Withrow

Stephen has over 30 years of experience in training, development, and consulting in a variety of technology areas including Python, Java, C, C++, XML, JavaScript, Tomcat, JBoss, Oracle, and DB2. His background includes design and implementation of business solutions on client/server, Web, and enterprise platforms. Stephen has a degree in Computer Science and Physics from Florida State University.

About Webucator

Webucator provides instructor-led training to students throughout the US and Canada. We have trained over 90,000 students from over 16,000 organizations on technologies such as Microsoft ASP.NET, Microsoft Office, Azure, Windows, Java, Adobe, Python, SQL, JavaScript, Angular and much more. Check out our complete course catalog.