How to execute my HelloWorld script

I am currently trying to run my first java script:

 public class HelloWorld { public static void main(String[] args) { System.out.println("Hello World"); } } 

I decided to take a look at Java. However, I come from languages ​​like JavaScript and PHP that do not require compilation or something like that.

So far, I think I’m compiling it correctly on the command line:

 C:\Users\Shawn>"C:\Program Files\Java\jdk1.7.0_25\bin\javac.exe" "HelloWorld.java" 

It adds a file called: HelloWorld.class , so I did something right.

However, now when I try to run the program using:

 C:\Users\Shawn>"C:\Program Files\Java\jdk1.7.0_25\bin\java.exe" "C:\Users\Shawn\HelloWorld.class" 

I get this, Error: Could not find or load main class C:\Users\Shawn\HelloWorld.class .

However, if I try the same command but use javac.exe , instead I get:

 javac: invalid flag: C:\Users\Shawn\HelloWorld.class Usage: javac <options> <source files> use -help for a list of possible options 

Why is this happening? Why is my program not running correctly?

+4
source share
3 answers

The java command accepts a class name, not a file name.
He then uses the Java class loader to find the .class file for this class in the current directory or class path.

When you go through HelloWorld.class , it searches for a class named class in the HelloWorld. package HelloWorld.
(it will be ./HelloWorld/class.class )

You need to go through HelloWorld .

+9
source

As others have pointed out, the argument should simply be the name of the class without the extension .class . However, the second requirement must be met: the class file must be in the path.

It is usually not recommended (although convenient) to include the current directory in the global classpath, but you can override it on the command line:

 java -cp . HelloWorld 

You can also specify an explicit path:

 java -cp "C:\Users\Shawn" HelloWorld 

If your Java program uses other classes, include the global class path as follows:

 java -cp "%CLASSPATH%;." HelloWorld 
0
source

See the following javac documentation for more information. especially the section on cross-compilation options.

0
source

Source: https://habr.com/ru/post/1492532/


All Articles