0

I'm learning how to compile and run java classes in terminal using the commands javac and java. I have no problem compiling and running an individual class, however, when I put that class into a package and try to run it, I get "Error: Could not find or load main class (class name)".

Currently, my directory structure is: ~/Desktop/OCA_Practice/cert the name of the file I'm running is called Test.java and I've placed it in a package called cert. Here is my very basic class:

package cert;
public class Test {
    public static void main(String args[]) {
        System.out.println("This is a test.");
    }
}

When I run the command javac Test.java in the cert directory, the class compiles successfully, however, when I try to run java Test after compiling, that's when I get the error. I've tried running my folder structure in addition to the class when I try to run the program, as in java Desktop.OCA_Practice.cert.Test and that didn't work. I've changed my package declaration inside my class to Desktop.OCA_Practice_Probs.cert and that didn't work either.

I've tried a large variety of different approaches with no success. Have I written the package name wrong in my class file? I ran the command: java -version and it shows that I'm running java version "1.8.0_25" so I'm pretty sure my class path is set correctly.

Thanks in advance for any responses.

1

When you run a class in Java, you need to give the full package name and class name, and be in the right place for that to match the folder and file name.

So in your case, declare package cert; in your class as you did initially, build it, then run it as follows:

cd ~/Desktop/OCA_Practice
java cert.Test
  • Thanks so much Stephen! I appreciate it, I had no clue I had to be in the parent folder of my package when trying to run a class in that package. – Street.lit Feb 12 '15 at 19:16
-2

To run a class in a package, always run the class from the parent directory of the package.
In your case change open terminal in directory OCA_Practice using command:
cd ~/Desktop/OCA_Practice
Then run the class file using package name after java by command:
java cert.Test

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.