Error: class X is public should be declared in a file named X.java

I am trying to write a program, but I'm getting this compiler error:

Main.java:1: error: class WeatherArray is public, should be declared in a file named WeatherArray.java
public class WeatherArray {
       ^
1 error

I have checked my file names, and my public class is the same as my .java file.

How can I fix this?

Here is my code:

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

Solution 1:

Name of public class must match the name of .java file in which it is placed (like public class Foo{} must be placed in Foo.java file). So either:

  • rename your file from Main.java to WeatherArray.java
  • rename the class from public class WeatherArray { to public class Main {

Solution 2:

The name of the public class within a file has to be the same as the name of that file.

So if your file declares class WeatherArray, it needs to be named WeatherArray.java