Zampanò
Zampanò

Reputation: 594

How to Properly Implement Packages in Java

I am learning how to use packages in Java, but I am running into trouble when trying to implement them. I have a simple class called Main which appears as follows:

public class Main
{
    public static void main(String[]args)
    {
        System.out.println("Package Test...");
    }
}

The directory of this class is: C:\Users\MyComputer\Desktop\Packages\Main.java

When I compile this class, I run into no trouble. However, when I add "package com.example.mypackage;" to the top of the .java file, compile the program, and try to run the program, I receive the following error: "Error: Could not find or load main class Main"

What can I do to solve this problem?

Upvotes: 0

Views: 90

Answers (1)

Ben Bynum
Ben Bynum

Reputation: 318

If the path of your class is C:\Users\MyComputer\Desktop\Packages\Main.java then your class is not in a package. In this instance "Packages" is your project folder, and it only contains the one java class.

If you want package com.example.mypackage; to work, then your path needs to be:

C:\Users\MyComputer\Desktop\Packages\com\example\mypackage\Main.java

Upvotes: 3

Related Questions