Understanding Java Compilation: -sourcepath and -classpath Explained

Understanding Java Compilation: -sourcepath and -classpath Explained Photo
Author: Tatyana Milkina

In this article, we will explore how to use the -sourcepath and -classpath options for compiling and running Java programs effectively.

  1. Compilation with -sourcepath
  2. What is Classpath?
  3. Using the -classpath Option
  4. Key Points

1. Compilation with -sourcepath

The -sourcepath option specifies directories where the compiler should look for the source file hierarchy.

Consider an example with two classes in different packages: first.Example1 and second.Example2. The first.Example1 class creates an instance of second.Example2:

package first;

import second.Example2;

public class Example1 {
    public static void main(String[] args) {
        Example2 example2 = new Example2();
        System.out.print("Done!");
    }
}

package second;

public class Example2 {
}

Here is the directory structure:

Directory structure for Java classes

Now, let's try compiling Example1.java as we normally do:

cd project1
javac -d classes src/first/Example1.java

The compilation fails with the following errors:

src\first\Example1.java:9: error: package second does not exist
        second.Example2 example2 = new second.Example2();
                                     ^
2 errors

This happens because the compiler doesn't know where to find Example2.java. To fix this, use the -sourcepath option:

javac -d classes -sourcepath src src/first/Example1.java

2. What is Classpath?

The classpath is used by the java and javac commands to locate other classes needed during compilation and runtime. It can be specified as:

  1. An environment variable (CLASSPATH).
  2. The -classpath or -cp option in the javac and java commands, which overrides the environment variable for a specific call.

Classpath methods

3. Using the -classpath Option

Suppose the second.Example2 class is in a different project and only its .class files are available. Here's the directory structure:

Java class structure for classpath

To compile first.Example1, use the following command:

cd projectExample1
javac -d classes -cp ../projectExample2/classes src/first/Example1.java

4. Key Points

  • -sourcepath specifies directories for source files.
  • -classpath (or -cp) specifies directories for compiled classes.
  • Use relative or absolute paths for both options as needed.
  • Including a subdirectory in the classpath doesn't automatically include the parent directory.
Курс 'Java для начинающих' на Udemy Курс 'Java для начинающих' на Udemy
Read also:
Comments