How to run java class file which is in different directory?
Last Updated :
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
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.
public 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.
- 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.
public 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.
-
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.
-
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.
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
Similar Reads
How is CompileTime classpath different from RunTime classpath in Java?
What is a Classpath? Classpath refers to the Path where all the classes/jars are available. What is Compile-time classpath? This classpath has all the classes/jars required to compile the application without any syntax error. Now we might think that our project compiled successfully so it will execu
2 min read
Java | Print root directories
In Java we can use listRoots() of File class to find all root directories. import java.io.*; public class GeeksforGeeks { public static void main(String[] args) { File[] rDirs = File.listRoots(); for (int i = 0; i < rDirs.length; i++) System.out.println(rDirs[i].toString()); } } Output (In Window
1 min read
Is main method compulsory in Java?
The answer to this question depends on the version of java you are using. Prior to JDK 7, the main method was not mandatory in a java program. You could write your full code under static block and it ran normally. The static block is first executed as soon as the class is loaded before the main(); t
2 min read
Compile and Run Java Programs in Sublime Text in Linux
Sublime Text is a free minimalist coding editor developed by Sublime HQ for desktop use. This development and IT program enable you to solely focus on your code, leaving all the other types of eye-candy out. Procedure: Open terminal and the specific command are entered there in order to check for th
2 min read
Java | Renaming a file
In Java we can rename a file using renameTo(newName) method that belongs to the File class. Declaration: Following is the declaration for java.io.File.renameTo(File dest) method: public boolean renameTo(File dest) Parameters: dest - The new abstract pathname for the existing abstract pathname. Excep
1 min read
Difference between #include in C/C++ and import in JAVA
#include in C/C++: In the case of C language, #include is a standard or user-defined file in a program that tells the preprocessor to insert the internal contents of another file into the source code of the program. Syntax: #include<stdio.h> Program 1:Below is a C Program to demonstrate the us
2 min read
How to Execute a .class File in Java?
A Java Class file is a compiled java file. It is compiled by the Java compiler into bytecode to be executed by the Java Virtual Machine. Step #1: Compile the .java File Open Terminal (Mac) or Command Prompt (Windows). Navigate to the folder containing the java file and type the following command to
1 min read
How to Set Destination of the Class File in Java?
In this article, Let's learn How to Set Destination of the Class File in Java. Before that, let's understand what is a class file. When we compile a java file, we get a class file. A Java class file is a file containing Java byte-code and having " .class" extension that can be executed by JVM. The j
1 min read
How to Read a File From the Classpath in Java?
Reading a file from the classpath concept in Java is important for Java Developers to understand. It is important because it plays a crucial role in the context of Resource Loading within applications. In Java, we can read a file from the classpath by using the Input Stream class. By loading the cla
3 min read
Java File Class
Java File class is a representation of a file or directory pathname. Because file and directory names have different formats on different platforms, a simple string is not adequate to name them. Java File class contains several methods for working with the pathname, deleting and renaming files, crea
6 min read