Davide Antipa
Davide Antipa

Reputation: 102

The declared package "" does not match the expected package "(file name)"

I'm new to Java and I'm using Visual Studio Code. When I run the code it works fine, but every program in java (even a basic Hello World program) gives me this error.

The declared package "" does not match the expected package "helloWorld"

I didn't find any solutions on internet and I don't know how to fix this.

here is the code:

public class helloworld {
    public static void main(String[] args) {
        
        System.out.println("hello world");
        
    }
}

Upvotes: 1

Views: 2627

Answers (2)

SHUBIKSHA
SHUBIKSHA

Reputation: 11

In Java, it's common practice to organize files into folders (known as "packages") to maintain a structured project. When you place a file inside a folder, Java expects you to declare the package at the beginning of the file.

To resolve this, add a package declaration at the beginning of your file. The format for this declaration is:

package [folder_name];

Replace [folder_name] with the name of the folder where the file is located.

Upvotes: 0

HaroldH
HaroldH

Reputation: 533

Based on your compiler error and the code you showed, you have the following folder/package structure in the project you have created:

src
|
|-helloWorld
       |
       | helloworld.java

If that's the case, the "expected package" is the full package definition your java file is defined in, in this case, "helloWorld"

If you had this other folder structure:

src
|
|-helloWorld (folder/package)
       |
       | subfolder (subfolder/package)
                 |
                 | helloworld.java

then your expected package for the class helloworld would be helloWorld.subfolder

To actually define that package in the .java file, you must write the following as the first code line of the file (this is mandatory):

package fullpackage;

In your example, this would be:

package helloWorld;

The full code example as I can see it, would be for you something like...

package helloWorld;
public class helloworld {
   // the rest of your main method and code here
}

Upvotes: 1

Related Questions