Why do I get a duplicate class error in Java?
What causes it
Java requires that each class has a unique fully qualified name (package + class name). If two different files define the same class in the same package, or if the same class appears on the classpath twice, you get this error.
It can also happen when you have a class in your source and also in a JAR file that's on the classpath, or when you accidentally copy a class file into multiple source roots.
- Two source files define the same class in the same package.
- A class exists both in your project and in a dependency JAR.
- You have multiple versions of the same library on the classpath.
- A generated source file conflicts with a handwritten one.
- You imported a class with the same simple name from two different packages.
How to fix it
First, identify where the duplicate is coming from. Check your source folders for files with the same class name, and check your dependencies for overlapping JARs.
If it's a conflict between your code and a library, rename your class or exclude the library. If it's two versions of the same library, align them to one version.
In build tools like Maven or Gradle, you can use dependency management to exclude transitive duplicates.
Common mistakes
- Thinking the error is about two classes with the same simple name in different packages; that's allowed if you use fully qualified names.
- Ignoring the full error message, which often tells you exactly which two locations conflict.
- Assuming it's a compiler bug when it's usually a classpath or source configuration issue.
