简体   繁体   中英

Java HelloWorld program run

I tried to run my basic HelloWorld.class file from my terminal.

I use the following input:

Java HelloWorld.class

But it says:

Error: Could not find or load "HelloWorld.class"

I have tried giving it a directory but it doesn't work.

because you didn't compiled or run it successufully.you should use

 javac HelloWorld.java

to complile and

then use

 java HelloWorld

to run it. plz check this tutorial http://introcs.cs.princeton.edu/java/11hello/

The class should be (Executable Class should definitely contain the main method with same declaration as below)

Class MyClassName
{
   // Methods here

   public static void main (String args[])
   {
       // Code here
   }
}

To Compile , it should be:

javac MyClassName.java

On successful compilation, MyClassName.class would be generated in your folder.

To run , it should be

java MyClassName

In case your java is in say D:/JavaWorkDir/src , You need to compile and run from the folder D:/JavaWorkDir/src . Also Ensure that your classpath is set appropiately.

You are receiving this error because you shouldn't include the .class when you run the compiled file.

After you've compiled:

javac HelloWorld.java

run using:

java HelloWorld

(don't do: java HelloWorld.class )

Run it as Java HelloWorld and not like Java HelloWorld.class .
The error Error: Could not find or load "HelloWorld.class" is occuring because:

  1. The class may have not compiled correctly.
  2. The compiled class is not available on the path from where you are trying to run it.
  3. Proper classpath is not set for compiling and running the java classes.

Whenever you write a Java Program named HelloWorld , you must compile it as:

javac HelloWorld.java

Once the HelloWorld.class class file generated in the same directory where you have your java file, compiled by the compiler, you can run it from console as:

java HelloWorld

You don't run it as

java HelloWorld.class

but

java HelloWorld

There is no need of .class extension.

But note you always have to use fully qualified name . So if your class resides in some package say myPackage then you need to run

java myPackage.HelloWorld

如果您想尝试世界,您也可以尝试在NetBeans应用程序和Jdoodle.com上运行它

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM