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

Running Packaged Classes

The java command requires fully qualified class names: java com.example.Main, not just Main.

Running Packaged Classes

What you'll learn: How to correctly execute Java classes that belong to a package using the java command.


When you've organized your code into packages, running it requires a slightly different approach than running classes in the default package. The java command needs to know the fully qualified class name — that is, the complete package path plus the class name.

Why Fully Qualified Names Matter

Think of packages like postal addresses. If you want to send a letter to "John Smith," the post office needs more than just the name — they need "John Smith, 123 Main Street, Springfield." Similarly, when Java searches for your Main class, it needs to know: "Which Main? The one in com.example or somewhere else?"

The Correct Syntax

If your class Main is declared in package com.example, you cannot simply run:

java Main

This tells Java to look for a class called Main in the default package, which will fail.

Instead, you must use:

java com.example.Main

The fully qualified name com.example.Main tells Java exactly where to find your class.

Running From the Correct Directory

Remember that packages map to directories. When you execute the java command, you should be in the root directory of your package structure (where com/ begins), not inside the package folder itself.

project/
└── com/
    └── example/
        └── Main.class

Run from the project/ directory:

java com.example.Main

Key Takeaway: When running packaged classes, always use the fully qualified class name with the java command: java packageName.ClassName, not just ClassName.