I have managed to compile java-program but I cannot execute it

我怕爱的太早我们不能终老 提交于 2019-12-02 00:27:06
  1. create a file called HelloWorld.java;
  2. paste the code posted below inside HelloWorld.java:
  3. compile it by executing the command: javac HelloWorld.java in the same folder as HelloWorld.java is in;
  4. execute the code by doing: java -cp . HelloWorld in the same folder as HelloWorld.java is in.

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

How the classpath works, can be read here: http://en.wikipedia.org/wiki/Classpath_%28Java%29

Just for clarity; you are saying that you have a class in the default package, that is you have not included a package specifier in the Java file, and your class is called HelloWorldApp. When you compiled this, you got a classfile HelloWorldApp.class in the current directory.

Assuming the above to be true then try:

java -cp . HelloWorldApp

For example, the following works on a unix box:

$ echo 'class HelloWorldApp { public static void main(String []argv) { System.out.println("Hello World!"); } }' > HelloWorldApp.java
$ javac HelloWorldApp.java 
$ java -cp . HelloWorldApp 
Hello World!

Of course, you should indent your code a little nicer than just shoving the whole thing onto one line ;-)

Edit: To answer the comment:

Normally, the default classpath is the runtime libraries and the current directory. However, if you have the CLASSPATH variable set, then this will override the default, and you need to explicitly set the classpath back to its "default value". To verify if the CLASSPATH environment variable is set, you can do (again assuming unix):

set | grep CLASSPATH

If it is set, that is why you need to manually include . on your classpath.

Have you included . and .. in your path? Just for clarification . represents your current directory and .. represents your parent directory. You are telling that the java has to search the current directory and the parent directory to find the class. Add the same to your classpath too.

What happens if you use:

java -cp {path to directory with HelloWorldApp in it} HelloWorldApp

That path should be contained within your CLASSPATH environment variable. Is that exported to your command shell ? Do you need to start a new command shell to get the most recent version of CLASSPATH ?

Post your code. I believe the problem is that your main class is not defined properly. I did this the other day.

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

The class path concept and the logical difference between Java source code and compiled byte code is notoriously hard to get right.

I would strongly recommend you familiarize yourself with the Sun Java Tutorial. The relevant section is

http://java.sun.com/docs/books/tutorial/getStarted/cupojava/win32.html

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!