souparno majumder souparno majumder - 1 year ago 68
Java Question

How to compile and run a java class with a package

I have a class called MyClass in the file MyClass.java file (code mentioned below)

package myclass;

class MyClass {
public int add (int a, int b){
return a+b;
}

public static void main(String args[]) {
MyClass obj = new MyClass();
System.out.println(oobj.add(2, 3));
}
}


I am compiling the class with

javac MyClass.java


But I am trying to run the class using

java MyClass


or

java myclass.MyClass


I am getting the Error

Error: Could not find or load main class MyClass


But, I am able to run this program if I omit out the package name.
where am I going wrong?

Answer Source

Make sure that you are inside the parent directory of the package folder (the folder in which your compiled class file is), and execute the following command:

java myclass.MyClass

Below is an example file structure:

bin
    -> myclass
        -> MyClass.class

In the example structure above, you would have to execute the command from the "bin" directory.

Also, define the class as public and recompile the java source file.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download