3

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?

isnvi23h4
  • 1,910
  • 1
  • 27
  • 45

4 Answers4

9

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.

SamTebbs33
  • 5,507
  • 3
  • 22
  • 44
4

I ran into this too. It's very frustrating for someone from other languages. The key here is, the java file has to be in the right directory depending on the package declaration.

if the java file Test1.java starts with

package com.xyz.tests;

Then the java file Test1.java needs to be in directory com/xyz/tests

You can compile and run as

javac com/xyz/tests/Test1.java
java com/xyz/tests/Test1

Good luck.

pktCoder
  • 1,105
  • 2
  • 15
  • 32
0

You Need To Compile The Class using :

javac -d ./myclass  
Smart Manoj
  • 5,230
  • 4
  • 34
  • 59
0

I get my example to run by

java <package>.<class>

From parent directory of package