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

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


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 {

This happens when you have 1 name for the Java class on hard disk and another name of Java class in the code!!

For example, I renamed my MainActivity class to MainnActivity only (!) in the code. I got this error immediately.

There is also a visual indicator in the Project tab of Android Studio - a class inside a class, like you have nested classed, but with an error indicator.

The solution is to simply rename class name in the Project tab (SHIFT + F6) to match the name in the Java code.

Tags:

Java