Home >Java >javaTutorial >Why Does My Java Compiler Show 'Error: class X is public, should be declared in a file named X.java'?

Why Does My Java Compiler Show 'Error: class X is public, should be declared in a file named X.java'?

Barbara Streisand
Barbara StreisandOriginal
2024-12-23 10:41:57275browse

Why Does My Java Compiler Show

Class Public Declaration Error

Issue:

When attempting to compile a Java program, a compiler error is encountered: "Error: class X is public, should be declared in a file named X.java."

Cause:

This error occurs when the public class within a .java file does not match the file's name.

Resolution:

To resolve this issue, there are two options:

  • Option 1: Rename the Java file to match the public class's name.

    • For example, if the public class is WeatherArray, rename the file to WeatherArray.java.
  • Option 2: Rename the public class to match the file's name.

    • For example, if the file is named Main.java, rename the public class to Main.

Example Code:

Here is the corrected code:

// WeatherArray.java
public class WeatherArray {
    public static void main(String[] args) {
        // ...
    }
}

Alternatively:

// Main.java
public class Main {
    public static void main(String[] args) {
        // ...
    }
}

The above is the detailed content of Why Does My Java Compiler Show 'Error: class X is public, should be declared in a file named X.java'?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn