Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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) {
        // ...
    }
}
like image 303
Chris Frank Avatar asked Oct 18 '22 02:10

Chris Frank


People also ask

Does a Java file need a public class?

java , so it doesn't need to go thru all packages ( which may contain multiple classes) it will now only search that package in which a source file A. java is present. So from compilation time , performance point if view one source file should have one public class.

What is the meaning of error class interface or enum expected in Java?

The class interface or enum expected error is a compile-time error in Java which arises due to curly braces. Typically, this error occurs when there is an additional curly brace at the end of the program.


1 Answers

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 {
like image 92
jlordo Avatar answered Oct 19 '22 16:10

jlordo