1

Having this file schema:

folder "a"
        |
        |_____ MyClass.java

Where my ".java" file has this code:

package a;

public class MyClass {
    public static void main(String[] args) {
        System.out.println("Hello world");

    }
}

I was wondering the reason why I get this error (I'm using visual studio, I say it in case it is related to my error):

The declared package "a" does not match the expected package "".

I've noticed that sometimes when I reopen my folder It suddenly works, however other times it doesn't.

I don't know why this happens, I believe the reason it's related to visual studio but it goes further of it, since when I try to compile it, as said, sometimes It works, others don't.

Telling me this error:

Error: Could not find or load main class MyClass
Caused by: java.lang.NoClassDefFoundError: a/MyClass (wrong name: MyClass)
Camy07
  • 53
  • 4
  • 4
    In Visual Studio, you need the "source folder" to be the folder above `a`, not `a` itself, because package names are resolved relative to the source folder. – Dawood ibn Kareem Jan 12 '23 at 18:58

1 Answers1

2
package a;

public class MyClass {
    public static void main(String[] args) {
        System.out.println("Hello world");

    }
}

It depends from where you are referencing the class. If a is a subfolder and you are trying to compile MyClass.java from within a it won't work (unless you specify the correct folder like ./.. or similar. Packages are relative to some root folder or other package.

WJS
  • 36,363
  • 4
  • 24
  • 39
  • Do you know any source which explains this "Relative behaviour" of packages more in depth? – Camy07 Jan 12 '23 at 19:18
  • 1
    I find this situation can be most troublesome when doing command line compiling with `javac`. So check out [How to compile java package structures using javac](https://stackoverflow.com/q/19382593/1552534) for more information. This can be related to most IDE's which have an expected root from which packages start. In `Eclipse`, that would be the source file `(src)` of the current project. – WJS Jan 12 '23 at 19:49