This week's book giveaway is in the OCAJP 8 forum. We're giving away four copies of OCA Java SE 8 Programmer I Study Guide and have Edward Finegan & Robert Liguori on-line! See this thread for details.
Guys, could you explain me some features of java and javac commands, please.
(1) I have a compiled package named 'solutiondatabase' based in the following folder: C:\Documents and Settings\MyName\workspace\SolutionDatabase\src\MyFiles
Consequently, 'solutiondatabase' folder with class files exists in MyFiles folder.
I want to run Main class of that package using 'java' command from the SolutionDatabase folder.
This command works:
java -cp src/MyFiles solutiondatabase.Main
My question is: can I do the same without classpath argument via specifying exact path to the compiled class? Can I do the same in case there are no package and I need to run only one compiled file?
I tried this, but it doesn't work:
(2) Here is a quote from the SCJP preparation guide: very common situation occurs in which java or javac complains that it can't find a class file, and yet you can see that the file is IN the current directory! When searching for class files, the java and javac commands don't search the current directory by default. hmm.. If I go to MyFiles folder (which contains compiled solutiondatabase folder with class files) and run - it works. javac works the same way. So, whether it really searches in the current folder, or not?
How can I run the compiled class files if I am exactly in the folder with that files, i.e. in the folder with the same name as my package (solutiondatabase) ?
(3) When specifying classpath, how can I input a folder two levels higher than current one?
Martin Vanyavchich wrote:But CLASSPATH dosen't include current dir by default.
That is true, but slightly confusing. If there is no system CLASSPATH set, the "java" and "javac" tools will assume the CLASSPATH is "." ie the current directory. There is therefore often no need to set a CLASSPATH variable. A lot of people who post here appear to do more harm than good by setting a system CLASSPATH.
I'd go a little stronger and say that that particular study guide is wrong, and I'd be suspicious of anything else it might say. The only default behavior is the behavior when CLASSPATH is unset, as no jdk installer sets it. And as was just stated, without CLASSPATH the effective class path is "." .
From this I can conclude the following:
- its impossible to run class from a package if class file is not located in the folder named packagename.
- if I want to run a class file from a package and I am in the folder with that file, to run it I'll have to include upper folder in the classpath and go from there: i.e. call java -cp ../ packagename.filename
- CLASSPATH variable cannot affect two previous statements
- if I use -cp parameter the current folder will not be searched, except for explicitly introducing it as '.'
Am I right?
author and iconoclast