## Why is this an issue?

The purpose of Java packages is to give structure to your project. A structure helps to mentally break down a project into smaller parts, simplifying readers' understanding of how components are connected and how they interact.

By convention, the source files' directory structure should replicate the project’s package structure. This is for the following reasons:

1. The mapping between the package name and the location of the source file of a class is straightforward. That is, the path to the source file is easier to find for a given fully qualified class name.
2. If two different structures are applied to the same project - one to the packages but another to the source file directories - this confuses developers while not providing any benefit.
3. The directory structure of the class files generated by the compiler will match the package structure, no matter the source file’s directory. It would not make sense to have one directory structure for the generated class files but a different one for the associated source files.

Similarly, a source directory should not have the character `.` in its name, as this would make it impossible to match the directory to the package structure.

## How to fix it

Either move the source file so that the relative file path within the source directory matches the package name, or change the package name so that it matches the relative file path.

### Code examples

#### Noncompliant code example

    // file: src/main/foo/Fubar.java
    package com.foo.bar;

    class Fubar {
    }

#### Compliant solution

    // file: src/main/com/foo/bar/Fubar.java
    package com.foo.bar;

    class Fubar {
    }

    // file: src/main/foo/Fubar.java
    package foo;

    class Fubar {
    }

## Resources

### Articles & blog posts

- Baeldung - Fixing the "Declared package does not match the expected package" Error
- Stackoverflow - Why do java source files require package declarations?
- tutorialspoint - What are the best practices to keep in mind while using packages in Java?