• Register

How to run a  .class file?

The JVM hunts for and loads classes in this order:

1.    bootstrap classes: the classes that are important to the Java Stage

2.    extension classes: packages that are in the extension directory of the JRE or JDK

Import word can introduce classes from the present classpath, external the classpath import can’t work. Nowadays assume you previously have a project in which you have used more or less utility classes, which you want in your another project also. Then in this condition import word doesn’t do the job.

Lets continue with the subsequent example .Here you have 2 projects project1 and project2. project1 comprises src and classes.

Subsequent are the stages to run java .class file:

·         Stage 1 (Create utility class): 

Create A.java in src directory comprising following code.

//java utility class

public class ABC


    public void testmethod()


        System.out.println("Testmethod() method of class A"); 




Here, We have one utility class that is A.

  Stage 2 (Compile utility class): 

Open terminal at project1 site and perform subsequent commands.   

tutorial/proj1>cd src
    tutorial/proj1/src>javac -d ../classes A.java

Stage 3 (See  A.java is effectively compiled):

 See in classes directory of project1 whereas  class file is formed or not

Stage 4 (Develope key class): 

Pass to your project2 directory. Here are also 2 directories for the equal aims. Generate MyMainClass.java in src directory.

//java class to execute program

public class MyMainClass{

    public static void main(String[] args){

        System.out.println("we are In main class"); 

        A abc1 = new A();





tutorial/project2>cd src
tutorial/project2/src>javac -d ../classes MyMainClass.java
MyMainClass.java:4: error: cannot find symbol
MyMainClass.java:4: error: cannot find symbol
2 errors

As you realize, there is an error that sign A is not found.

Stage 5 (Compile with -cp option):

·         tutorial/project2>cd src
·         tutorial/project2/src>javac -d ../classes -cp 
·         ../../project1/classes MyMainClass.java

Here, your code will be compiled effectively and MyMainClass.class is created in the classes directory.

Stage 6 (Execute the program):

 Attempt to execute the program.

tutorial/proj2/src>cd ../classes
tutorial/proj2/classes>java MyMainClass
Exception in thread "main" java.lang.NoClassDefFoundError: A
        at MyMainClass.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)

Oops, we got an error that class A is not found.

Stage 7 (Execute with -cp option): 

We are supposed to achieve  the path of class A.

tutorial/project2/classes>java -cp ../../project1/classes; MyMainClass
·         In main class
·         Testmethod() method of class A

Now, you have effectively run  program.

2,760 points
7 4