Big Moose Saloon
 Search | Java FAQ | Recent Topics Register / Login

# Compiling with javac and -cp

Jon Greenwood
Greenhorn

Joined: Mar 13, 2011
Posts: 11
Hi

javac resides in C:\Program Files\Java\jdk1.6.0_24\bin

I have the following Environment Variables
JAVA_HOME C:\Program Files\Java\jdk1.6.0_24
PATH %JAVA_HOME%\bin;

my HelloWorld.java src file resides in C:\java

I can correctly compile from the working directory
C:\java>javac HelloWorld.java

Which I think actually defaults to
C:\java>javac -cp . HelloWorld.java
where the period[.] is the current directory

What is the correct syntax if I try to compile from the previous parent directory?
C:>
Note: I specifically want to use the -cp argument and not set CLASSPATH=

Presumably I need to navigate from the javac.exe?

Amit N Chudasama
Greenhorn

Joined: Nov 08, 2011
Posts: 2

Probably you can do it like below ... but at first WHY do you want this ?

C:\>javac -cp . java\HelloWorld.java

OR

C:\>javac java\HelloWorld.java

John Jai
Bartender

Joined: May 31, 2011
Posts: 1776
-cp option is used to find the .class files (or jars) that will be referred in the source files (.java) files.

So as Amit said this is the way to compile if source file is in different folder

C:\>javac java\HelloWorld.java

And below command is just looking for referenced class files in the current directory, but takes the source path from the java folder.
And hence it's very much equivalent to the above command.

C:\>javac -cp . java\HelloWorld.java

And since the -cp points to the .class files, you can use it in the java command without specifying its parent folder like below.

java -cp .\java HelloWorld

In the above command, the java tool looks for HelloWorld.class in the specified java folder...
Stephan van Hulst
Bartender

Joined: Sep 20, 2010
Posts: 3096

2
It's pretty simple. Just use the -sourcepath switch to specify where to find the source files.

For example: javac -sourcepath C:\Projects\MyProject\src -d C:\Projects\MyProject\bin com\example\HelloWorld.java

Actually, now that I investigated a bit more, you can't do this. -sourcepath only works for classes referenced by the source you're trying to compile. You still need to name the main class explicitly:
javac -sourcepath C:\Projects\MyProject\src -d C:\Projects\MyProject\bin C:\Projects\MyProject\src\com\example\HelloWorld.java

It's easier to just create a batch file in your project folder and do the following:
javac -cp src -d bin com\example\HelloWorld.java
John Jai
Bartender

Joined: May 31, 2011
Posts: 1776
And better rename the folder java to say "source" to avoid confusion
Jon Greenwood
Greenhorn

Joined: Mar 13, 2011
Posts: 11

It is sorta covered in the JavaRanch Style Guide.

subject: Compiling with javac and -cp
println
I'm having trouble with Java 1.6