0

I'm learning Java from the ground up, and I'm hoping someone can help me with an infuriating problem I've encountered. Here's the source code that works after I run "javac Example", and "java Example":

class Example {
    public static void main (String args[]){
        System.out.println("This is an example class");
    }
}

But if I try:

package examples;
class Example {
    public static void main (String args[]){
        System.out.println("This is an example class");
    }
}

...it goes to hell, and I get "Error: Could not find or load main class Example Caused by: java.lang.ClassNotFoundException: Example" returned to me.

I've trawled many resources on the net, which all say the same thing about getting the classpath right (which I've been over many times as of this typing), and none of the solutions work. Please assist if you can. Thanks.

rusrs
  • 1
  • 2
    If you add the package, the class is no longer called `Example`. It is now `examples.Example`. You have to adjust the command to launch it accordingly. Also, you will likely have to move this file into a directory called "examples" in order for the classloader to find it. – Thilo Apr 09 '20 at 09:50
  • Thanks, Thilo. I tried both those solutions, but they didn't work. – rusrs Apr 09 '20 at 10:05
  • What error are you getting exactly? Does it compile? Where does the compiler place the class file? What is the exact command you try to run? Where are class and source files relative to the working directory? – Thilo Apr 09 '20 at 10:24
  • When I try to run "java Example" after compiling "javac -cp . Example.java", the console returns "Error: Could not find or load main class Example Caused by: java.lang.ClassNotFoundException: Example". I did find one error in the source code - I was using the reserved keyword "Example", and changed that to "Ex". But that hasn't helped the situation. I'm still at square one. The source and class files are in the same working directory "c:\examples". – rusrs Apr 09 '20 at 12:35
  • Example is not a reserved keyword. Why did you run `java Example`? If you add the package, the class is no longer called `Example`. It is now called `examples.Example`. You have to adjust the command to launch it accordingly. – Thilo Apr 10 '20 at 02:40
  • Thanks. Thilo. I've tried that too, but it doesn't work. – rusrs Apr 11 '20 at 06:16

1 Answers1

-1

When I was a beginner I used Eclipse to code in java and run programs. You have to compile, Eclipse do it for you. So try using Eclipse. That's a free advice. Or else here is a link to help you : https://javarevisited.blogspot.com/2015/04/error-could-not-find-or-load-main-class-helloworld-java.html

daiboss
  • 7
  • 2
  • Thanks for your input daiboss, but unfortunately none of those solutions worked for me. – rusrs Apr 09 '20 at 09:59