Reputation: 17
I'm trying to execute a simple java program ("HelloWorld") in command prompt without using the set path option or setting the system variable. Suppose the java program is in D:\My_Programs and the java executable files are in C:\Program Files\Java\jdk1.6.0_24\bin. Here's what I did to compile: C:\Program Files\Java\jdk1.6.0_24\bin>javac D:\My_Programs\HelloWorld.java It is creating a .class file but the same strategy for execution creates an exception: C:\Program Files\Java\jdk1.6.0_24\bin>java D:\My_Programs\HelloWorld
Exception in thread "main" java.lang.NoClassDefFoundError: D:\My_Programs\HelloW
orld
Caused by: java.lang.ClassNotFoundException: D:\My_Programs\HelloWorld
at java.net.URLClassLoader$1.run(URLClassLoader.java:202)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:190)
at java.lang.ClassLoader.loadClass(ClassLoader.java:307)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:301)
at java.lang.ClassLoader.loadClass(ClassLoader.java:248)
Could not find the main class: D:\My_Programs\HelloWorld. Program will exit.
Can someone suggest on how to execute this file. Thanks in advance for your help.
The code:
class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello World!");
}
}
Upvotes: 0
Views: 13578
Reputation: 366
Before running the .java file in cmd, rename the file to the class name only then will it work. For example in this case, save the notepad file as 'HelloWorld.java'
Upvotes: 0
Reputation: 1
You can also try with changing your directory in cmd by cd D:\My_Programs and then execute java HelloWorld. it will execute the file. The only pre condition is that class file should be present at that location.
Upvotes: 0
Reputation: 11
java -cp D:\My_Programs HelloWorld
Because the directory hierarchy from the class hierarchy to be considered.
Upvotes: 0
Reputation: 66263
Please try this one:
C:\Program Files\Java\jdk1.6.0_24\bin>java -cp D:\My_Programs HelloWorld
or even that one:
C:\anywhere> C:\Program Files\Java\jdk1.6.0_24\bin\java -cp D:\My_Programs HelloWorld
The -cp
tells the java
executable where to look for the class HelloWorld
. Giving a file-like argument D:\My_Programms\HelloWorld
where Java assumes a pure packagename+classname will not work.
Upvotes: 7
Reputation: 216
You can try this way java -cp "D:\My_Programs" HelloWorld,the precondition is that HelloWorld.java you compiled is a main class.
Upvotes: 0
Reputation: 182832
Since you were in the Java directory rather than the directory of your program when you ran javac
the class file is probably there as well. That's generally a bad thing - you want javac
and java
to be in your path so you can execute them while you're in your program directory. And then you can execute the program using java HelloWorld
Upvotes: 2