I am trying to run a java program from command line. I tried following the steps mentioned here. But when I try to run javac Hello.java, it's throwing error that such a program is not there. I tried giving java Hello.java and got the error:
Exception in thread "main" java.lang.NoClassDefFoundError: Hello/java
Caused by: java.lang.ClassNotFoundException: Hello.java
at java.net.URLClassLoader1ドル.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
Could not find the main class: Hello.java. Program will exit.
What is the problem here. How can I do it?
EDIT: I have many classes in my code file, Hello.java. Will that cause any problem?
-
Are you using packages? do you see Hello.class?codaddict– codaddict2010年10月27日 15:13:05 +00:00Commented Oct 27, 2010 at 15:13
5 Answers 5
First you should compile the java code with
javac Hello.java
Then run it
java Hello
In both cases, make sure your classpath is set correctly...
2 Comments
To run the program you need to do:
java Hello
which is java followed by the class name without extension.
4 Comments
java Hello it still doesnt work ? And can you put the stacktrace you get when running java Hello ?First off, java requires at most one public class per file. No
public class this {
}
public class that {
}
You can have
class this {
class that {
}
}
if you need.
EDIT or in file this.java:
public class this {
}
class that {
}
javac won't be in the jre folder. Have you installed the jdk? it doesn't come by default on many computers. it's often in "C:\Program Files\Java\jdk1.6.0_05\bin\javac.exe" or a similiar path.
3 Comments
As stated by the others answer, first, you have to run your application using java Hello and not java Hello.java
Second, you have to check that your CLASSPATH is correctly set. It seems that your variable is not set or does not integrate the current directory, i.e. .
So run :
javac -classpath . Hello.java
java -classpath Hello
or
set CLASSPATH=.
javac Hello.java
java Hello
Of course, defining the CLASSPATH as a user / system variable in your Windows system is a better solution!
Comments
In case Hello.java is contained in a package, you will have to create an appropriate directory structure. I.e. in case Hello.java is contained in the package com.stackoverflow, you must create the folders com/stackoverflow and put Hello.java in this folder. From the root folder you must then launch
java com.stackoverflow.Hello