How to run java class file which is in different directory? - GeeksforGeeks

07 May, 2019
In this article, we will learn about how to use other project’s utilities, classes, and members. Before proceeding let’s learn about some keywords.
classpath
Classpath is the location from where JVM starts execution of a program. Similar to the classic dynamic loading behavior, when executing Java programs, the Java Virtual Machine finds and loads classes lazily (it loads the bytecode of a class only when the class is first used). The classpath tells Java where to look in the filesystem for files defining these classes. Variables and methods which are accessible and available at classpath are known as classpath variables. By default JVM always access the classpath classes while executing a program. JVM always go into the deep of classpath to search for a class or resource.
The JVM searches for and loads classes in this order:
bootstrap classes: the classes that are fundamental to the Java Platform (comprising the public classes of the Java Class Library, and the private classes that are necessary for this library to be functional).extension classes: packages that are in the extension directory of the JRE or JDK, jre/lib/ext/ user-defined packages and libraries
bootstrap classes: the classes that are fundamental to the Java Platform (comprising the public classes of the Java Class Library, and the private classes that are necessary for this library to be functional).
extension classes: packages that are in the extension directory of the JRE or JDK, jre/lib/ext/ user-defined packages and libraries
Using import keyword
import keyword is used in Java to import classes from current project’s classpath. You can import classes from different packages but from same classpath. It is to be remembered that packaging of a class starts from classpath. Suppose you have directory structure as follows:
a > b > c > d > class A

and your classpath starts from c, then your class should be in package d not in a.b.c.d.
Using classpath -cp option
import keyword can import classes from the current classpath, outside the classpath import can’t be used. Now suppose you already have a project in which you have used some utility classes, which you need in your second project also. Then in this situation import keyword doesn’t work because your first project is at another classpath. In that case, you can use -cp command while compiling and executing your program.
Let’s proceed with the following example. Create a directory structure as shown in the figure below.
Here you have 2 projects proj1 and proj2. proj1 contains src and classes. In the src directory, we will keep .java files that are source files and in classes directory, we will keep .classes files that are files generated after compiling the project.Following are the steps to run java class file which is in different directory:
Step 1 (Create utility class): Create A.java in src directory containing following code.//java utility classpublic class A{    public void test()    {        System.out.println("Test() method of class A");    }}Here, We have one utility class that is A.
//java utility classpublic class A{    public void test()    {        System.out.println("Test() method of class A");    }}
Here, We have one utility class that is A.
Step 2 (Compile utility class): Open terminal at proj1 location and execute following commands.cp_tutorial/proj1>cd src
cp_tutorial/proj1/src>javac -d ../classes A.java
-d option: It is used to store the output to different directory. If we don’t use this option then the class file will be created in the src directory. But it’s a good practice to keep source and class files separately. after -d option we provide the location of the directory in which class files should be stored.If there is any compile time error please resolve it before going further.
cp_tutorial/proj1>cd src
cp_tutorial/proj1/src>javac -d ../classes A.java

-d option: It is used to store the output to different directory. If we don’t use this option then the class file will be created in the src directory. But it’s a good practice to keep source and class files separately. after -d option we provide the location of the directory in which class files should be stored.If there is any compile time error please resolve it before going further.
Step 3 (Check whether A.java is successfully compiled): Check in classes directory of proj1 whether class file is created or not. It will be certainly Yes if your program was Compiled successfully.
Step 4 (Write main class and compile it): Move to your proj2 directory. Here are also 2 directories for the same reasons. Create MainClass.java in src directory having the following content and try to compile it.//java class to execute programpublic class MainClass{    public static void main(String[] args){        System.out.println("In main class");        A a1 = new A();        a1.test();    }}cp_tutorial/proj2>cd src
cp_tutorial/proj2/src>javac -d ../classes MainClass.java
MainClass.java:4: error: cannot find symbol
                A a1 = new A();
                ^
  symbol:   class A
  location: class MainClass
MainClass.java:4: error: cannot find symbol
                A a1 = new A();
                           ^
  symbol:   class A
  location: class MainClass
2 errors
As you see, there is a compile time error that symbol A is not found. If, we want to use class A of proj1 then we have to use -cp option to include proj1’s resources as shown in next step.
//java class to execute programpublic class MainClass{    public static void main(String[] args){        System.out.println("In main class");        A a1 = new A();        a1.test();    }}
cp_tutorial/proj2>cd src
cp_tutorial/proj2/src>javac -d ../classes MainClass.java
MainClass.java:4: error: cannot find symbol
                A a1 = new A();
                ^
  symbol:   class A
  location: class MainClass
MainClass.java:4: error: cannot find symbol
                A a1 = new A();
                           ^
  symbol:   class A
  location: class MainClass
2 errors

As you see, there is a compile time error that symbol A is not found. If, we want to use class A of proj1 then we have to use -cp option to include proj1’s resources as shown in next step.
Step 5 (Compile with -cp option):cp_tutorial/proj2>cd src
cp_tutorial/proj2/src>javac -d ../classes -cp 
../../proj1/classes MainClass.java
Now, your code will be compiled successfully and MainClass.class is created in the classes directory. -cp stands for classpath and it includes the path given with current classpath and once it is included JVM recognizes the symbol A that it is a class and compiles the file successfully.
cp_tutorial/proj2>cd src
cp_tutorial/proj2/src>javac -d ../classes -cp 
../../proj1/classes MainClass.java

Now, your code will be compiled successfully and MainClass.class is created in the classes directory. -cp stands for classpath and it includes the path given with current classpath and once it is included JVM recognizes the symbol A that it is a class and compiles the file successfully.
Step 6 (Execute the program): Try executing the program.execute the following commands to run your program.cp_tutorial/proj2/src>cd ../classes
cp_tutorial/proj2/classes>java MainClass
Exception in thread "main" java.lang.NoClassDefFoundError: A
        at MainClass.main(MainClass.java:4)
Caused by: java.lang.ClassNotFoundException: A
        at java.net.URLClassLoader$1.run(Unknown Source)
        at java.net.URLClassLoader$1.run(Unknown Source)
        at java.security.AccessController.doPrivileged(Native Method)
        at java.net.URLClassLoader.findClass(Unknown Source)
        at java.lang.ClassLoader.loadClass(Unknown Source)
        at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
        at java.lang.ClassLoader.loadClass(Unknown Source)
        ... 1 more
Oops, we got an error that class A is not found. This is because you tell JVM about A’s path at compile time only. While running the MainClass, he doesn’t know that there is a class A in other projects.
execute the following commands to run your program.
cp_tutorial/proj2/src>cd ../classes
cp_tutorial/proj2/classes>java MainClass
Exception in thread "main" java.lang.NoClassDefFoundError: A
        at MainClass.main(MainClass.java:4)
Caused by: java.lang.ClassNotFoundException: A
        at java.net.URLClassLoader$1.run(Unknown Source)
        at java.net.URLClassLoader$1.run(Unknown Source)
        at java.security.AccessController.doPrivileged(Native Method)
        at java.net.URLClassLoader.findClass(Unknown Source)
        at java.lang.ClassLoader.loadClass(Unknown Source)
        at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
        at java.lang.ClassLoader.loadClass(Unknown Source)
        ... 1 more

Oops, we got an error that class A is not found. This is because you tell JVM about A’s path at compile time only. While running the MainClass, he doesn’t know that there is a class A in other projects.
Step 7 (Execute with -cp option): We have to again provide the path of class A.cp_tutorial/proj2/classes>java -cp ../../proj1/classes; MainClass
In main class
Test() method of class A
Now, you have successfully run your program. Don’t forget to include ‘;’ after provided classpath. Replace ‘;’ with ‘:’ for OS/Linux.
cp_tutorial/proj2/classes>java -cp ../../proj1/classes; MainClass
In main class
Test() method of class A

Now, you have successfully run your program. Don’t forget to include ‘;’ after provided classpath. Replace ‘;’ with ‘:’ for OS/Linux.
How to run a java class with a jar in the classpath?
You can also use jar file instead of class files from different classpath. The process will be same, you just have to replace classes folder with jar folder and class name with jar name.Suppose you have jar file in the lib directory, then to compile you can use
cp_tutorial/proj2/src>javac -d ../classes -cp ../../proj1/lib MainClass.java

and to execute
cp_tutorial/proj2/classes>java -cp ../../proj1/lib; MainClass
Related Article: Setting up Java Environment
This article is contributed by Vishal Garg. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Achint Sharma
Akanksha_Rai
java-file-handling
Java-I/O
java-puzzle
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Initialize an ArrayList in Java
HashMap in Java with Examples
Interfaces in Java
ArrayList in Java
Multidimensional Arrays in Java
Overriding in Java
Stack Class in Java
Set in Java
LinkedList in Java
Singleton Class in Java