Example:
If there is a file HelloWorld.java in c:\xyz\javaprograms\HelloWorld.java
in the command prompt at the following default directory:
c:\users\username>javac c:\xyz\javaprograms\HelloWorld.java
it will compile and create a c:\xyz\javaprograms\HelloWorld.class
Now if I try to execute the program:
c:\users\username>java c:\xyz\javaprograms\HelloWorld
it says it did not find that file name.
if I go to the file path and execute the HelloWorld program (bytecode) then it runs fine
c:\xyz\javaprograms> java HelloWorld
Why did the java command not recognize the file with complete file path and why did it recognize the file only after going to the actual directory where the file is located?
You don't pass a filename to the java
command - you just pass a classname, and the classloader has to know how to load a class with that name.
It worked when you were in the right directory, because the current directory is implicitly on the classpath - but you don't have to do it that way:
c:\users\username>java -cp c:\xyz\javaprograms HelloWorld
should work fine too.
See more on this question at Stackoverflow