Course contentsShow
← Java
Lesson 663 of 2,87016. Packages, Imports, and JAR FilesFree lesson

Compiling Packaged Classes

Using javac with -d flag to specify output directory and maintain package structure in compiled .class files.

Compiling Packaged Classes

You'll learn how to compile Java classes that belong to packages and maintain their proper directory structure.

When you declare a class in a package, you need to compile it in a way that preserves the package structure. The Java compiler doesn't automatically create the directory hierarchy your packages require—you need to tell it where to put the compiled .class files.

The -d Flag: Your Directory Organizer

The javac command accepts a -d flag (short for "destination") that specifies where compiled classes should go. The compiler will automatically create the necessary package directories inside that location.

Syntax:

javac -d <output_directory> <source_file>

How It Works

Imagine you have a source file Person.java:

package com.company.model;

public class Person {
    private String name;
}

If you compile without -d:

javac Person.java

The Person.class file appears in your current directory—not where it belongs according to the package structure.

The correct approach:

javac -d . Person.java

The . means "current directory as root." The compiler creates:

./com/company/model/Person.class

Think of -d as telling the compiler: "This is the base location; please build the package folders inside it."

Common Output Directories

  • javac -d . MyClass.java — use current directory as root
  • javac -d bin MyClass.java — create package structure inside a bin folder
  • javac -d out MyClass.java — use an out folder for compiled classes

Key Takeaway: Use javac -d <directory> to compile packaged classes so the compiler automatically creates and maintains the correct package directory structure for your .class files.