Search code examples
javaprogram-entry-point

error: could not find or load main class <class Name>


package demo;
import java.io.*;
class A
{
    public void run()
    {
        System.out.println("This Is Class A : public void run()");
    }
}
class B
{
    public static void main(String args[])
    {
        System.out.println("Main Method Executed");
        A obj1 = new A();
        obj1.run();
    }
}

Compile :

d:\java>javac -d . demo.java

---> class file be created in directory demo [ A.class, B.class]

Run : d:\java>java B
Error: could not find or load main class B

but if I remove the line 1 [package demo;] than it run proper. so, when we use package name than why "Error: could not find or load main class B" error be generated.


Solution

  • Run this command. Because main method is in B class. The name of the package is demo and class containing main method is B.

    java demo.B
    

    Output :
    Main Method Executed
    This Is Class A : public void run()

    but if I remove the line 1 [package demo;] than it run proper.

    This because when you provide the package declaration in your program, then your classes reside in the package. So you need to provide the complete path to access them from your package.