The Big Moose Saloon Question and Answer of the Month

Mosey on in and pull up a stool. The JavaRanch Big Moose Saloon is the place to get your Java questions answered. Our bartenders keep the peace, and folks are pretty friendly anyways, so don't be shy!

Over in The Java In General (Beginner) Forum, JavaRanch's founder, Kathy Sierra, did a heck of a job tellin' folks about that dot in the whole CLASSPATH thing. Following is an excerpt from the original forum thread.

Question: Why do we define . in the Java classpath environment setting?

Answer: Both the compiler and the JVM need to find any of the classes that you're using in your code. If those classes are from the standard edition API, then no problem -- both java and javac know where *those* are. But they don't know about your *own* classes... the ones you're writing.

So... if you have a class that you just wrote, in a directory "foo", and the class is NOT in a package, then you cd to directory "foo" and then compile from that directory. That's the simplest way, to start out with. Including the dot "." in your classpath is the way you tell they system to "when you're looking for classes, be sure to look in the current directory (i.e. the one you cd to)."

Where to put that "."? You can add it permanently to your classpath as an environment variable in DOS (via autoexec.bat, if you're still on Windows 98!), or a property in Windows NT (I think -- can't remember it's been so long since I've seen NT). Or if you're on some flavor of Unix (including Mac OSX), you can put it in one of several places, including your .cshrc file (or whatever your initialization file is for your particular shell).

That's my preferred way... I never have to think about the current directory that way. (And you can still override that if you do NOT want the current directory to be included, which is sometimes necessary with RMI, but that's another story...)

Or, you can make sure that you have the "." by using the -classpath flag with java and javac:

java -classpath . MyClass

Or, you can do it just for your current terminal session, by using whatever it is you have to do for your particular shell. Something like:


(this says, "Take the current classpath, and add the current directory (.) to it, and then make that the new classpath setting for as long as this terminal is active.")

%java MyClass

(this is not necessarily *real* syntax)

If you use packages, it gets a little more complicated, although you'll still need the "." on the classpath.

What has troubled some programmers is that they are using an IDE which makes all kinds of settings for the classpath, and which may NOT include the current directory. That's when it's probably easiest to just use the -classpath flag:

javac -classpath .

There is of course more to the story than this, but if you're just starting out, this should work fine.