Im trying to execute a simple java code (I have already compiled it with no problems) but it gives me the next error:
c:\Users\alejandro\Desktop> java HelloWorld.java Error: Couldn't find or load the main class.
The code is the next:
public class HelloWorld{
public static void main(String[] args){
System.out.println("Hello world!");
}
}
-I have set the PATH variable correctly. -I have deleted CLASSPATH variable. -I have both files (.java and .class) in my Desktop.
You're specifying the name of the source file. That's not what you provide to the java
command - you specify the class name.
java HelloWorld
This assumes that HelloWorld.class
is somewhere on the classpath, which would default to "the current directory".
If you had a package, e.g.
package foo;
public class HelloWorld {
...
}
Then you would want to put HelloWorld.java
in a directory called foo
, and compile and run from the root directory:
> javac foo\HelloWorld.java
> java foo.HelloWorld
Note how now the fully-qualified class name is foo.HelloWorld
, not foo\HelloWorld
.
See more on this question at Stackoverflow