How we can run java class file which is in different directory?

In this text, we are able to find out about a way to use different project utilities, training, and members. Earlier than proceeding let’s study a few keywords.

classpath

Classpath is the vicinity from where JVM starts offevolved execution of an application. Similar to the traditional dynamic loading conduct, when executing java applications, the java virtual machine unearths and masses classes lazily (it hundreds the bytecode of a category handiest when the magnificence is first used). The classpath tells java were to look inside the filesystem for files defining these instructions. Variables and methods which can be handy and to be had at classpath are referred to as classpath variables. By way of default JVM continually gets admission to the classpath training whilst executing software. JVM always goes into the deep of classpath to look for a class or resource.

The JVM searches for and loads classes in this order:

  1. bootstrap classes: The lessons which might be fundamental to the java platform (comprising the general public lessons of the java magnificence library, and the personal classes which are essential for this library to be useful).
  2. extension classes: Programs that might be within the extension directory of the JRE or JDK, JRE/lib/ext/ consumer-defined programs, and libraries

Using import keyword

Import key-word is used in java to import classes from modern venture’s classpath. You may import lessons from distinct applications but from the identical classpath. It's far to be remembered that the packaging of a class starts off evolved from the classpath. Think you've got listing shape as follows:

a > b > c > d > class A

and your classpath starts from c, then your class should be packaged not in a.b.c.d.

Using classpath -cp option

Import keyword can import training from the modern classpath, outdoor the classpath import can’t be used. Now suppose you have already got a undertaking in which you have used a few utility training, that you want on your 2d challenge also. Then in this situation import key-word doesn’t work due to the fact your first undertaking is at another classpath. In that case, you may use -cp command whilst compiling and executing your software. Let’s continue with the subsequent example. Create a listing shape as shown inside the parent below.

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 class
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 place and execute following instructions.
cp_tutorial/proj1>cd src
cp_tutorial/proj1/src>javac -d ../classes A.java

-d alternative: it's far used to shop the output to unique listing. If we don’t use this feature then the elegance record might be created in the src listing. However it’s a great practice to maintain source and sophistication files one after the other. After -d choice we provide the vicinity of the listing wherein class documents must be stored. If there's any bring together time blunders please resolve it earlier than going further.

  • Step 3 (Check whether A.java is successfully compiled): Take a look at in training directory of proj1 whether or not elegance file is created or not. It will likely be surely sure in case your program became compiled correctly.
  • Step 4 (Write main class and compile it): Move on your proj2 listing. Here are also 2 directories for the same motives. Create mainclass. Java in src directory having the following content and try to assemble it.
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 might be compiled successfully and mainclass. Class is created inside the training listing. -cp stands for classpath and it includes the path given with contemporary classpath and as soon as it's far covered jvm recognizes the image a that it's far a category and compiles the record efficaciously.

  • Step 6 (Execute the program): Attempt executing the program. Execute the following commands to run your application.
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):
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 may additionally use jar document in place of magnificence documents from unique classpath. The procedure might be equal, you simply should replace classes folder with jar folder and sophistication name with jar call. Assume you've got jar file in the lib listing, then to bring together you may 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

 

Submit Your Programming Assignment Details