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

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

DDD
Release: 2024-12-26 13:56:11
Original
552 people have browsed it

Why Does My Java Code Throw a

Class Declaration Discrepancy Error

Problem:

When attempting to compile a Java program, an error occurs stating: "class X is public, should be declared in a file named X.java." Despite confirming that the class name and file name match, the error persists.

Answer:

In Java, the name of a public class must exactly match the name of the .java file in which it is defined. This is a requirement for the correct compilation and execution of the program.

Solution:

To resolve this error, there are two options:

  • Rename the file: Change the file name to match the public class name. For example, if the public class is named WeatherArray, rename the file to WeatherArray.java.
  • Rename the class: Change the public class name to match the file name. For example, if the file is named Main.java, change the class name to public class Main.

Once one of these modifications is made, the error will be resolved, and the program should compile successfully.

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

source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template