I came across this issue whilst attempting a practice question in Sierra & Bates p818 q12.
Suppose I have HelloWorld.java and a directory testdir in the current directory.
I can compile HelloWorld, even if I supply a command line classpath that does not include the current directory:
javac -classpath testdir HelloWorld.java
So, given that the file I want to compile was supplied as an argument, javac can find it, even though the supplied classpath didn't tell it to look in the current directory. (Were HelloWorld.java to use some other class, also in this same directory, the compile would fail.)
Now I try to launch HelloWorld.class, using the same classpath:
The classpath is only used to search class files - not source files. So, javac is not using the classpath to find your HelloWorld.java source file - it just looks in the current directory and finds it there.
If your HelloWorld class references other classes, then javac would use the classpath to find the class files for those classes.
Also, note that javac takes the file name of a source file, for example HelloWorld.java, as an argument, while java takes a class name (not a file name).
think of classpath as CLASS SEARCH PATH. it contains path for searching of .class files and not .java files. by default javac will look in current directory for any source files or class files. if you have set classpath environment variable then the default path ( . ) is overridden(so that you have to include current directory in your classpath if you want the javac and java binaries to look in your current directory). just for additional information , corresponding to -classpath switch there is another option -sourcepath and as you have guessed this is for the searching of source file path. this is useful for e.g. suppose you are compiling a source file Test.java , which requires A.java, B.java which are in c:/Demo dir. then for this the command will be javac -sourcepath c:/Demo Test.java. this will compile all the 3 source files.
OCPJP 6(100 %) OCEWCD 6(91 %) OCPJBCD(93%)
Joined: Feb 15, 2012
classpath is only used to search class files - not source files
Now you point this out, it's obvious! Thank you.
I now notice that javac also has a -sourcepath option. I'll have a play with that too.