How to Fix Class X Is Public Should Be Declared in a File Named X.java Error

Mehvish Ashiq Feb 12, 2024
  1. Cause of the class X is public, should be declared in a file named X.java Error
  2. Fix the class X is public, should be declared in a file named X.java Error
How to Fix Class X Is Public Should Be Declared in a File Named X.java Error

Today, we will go through various stages, starting from demonstrating a compile time error stating class X is public should be declared in a file named X.java. Then, we will see the reason causing this error, which will lead to its solution via code example.

Cause of the class X is public, should be declared in a file named X.java Error

Example Code Containing the Specified Error (Main.java file):

public class Test {
  public static void main(String[] param) {
    HiWorld();
    System.exit(0);
  }

  public static void HiWorld() {
    System.out.println("Hi World");
  }
}

We have this code in a file named Main.java while the class name is Test. Now, compile the code using the javac command as follows.

javac Main.java

As soon as we press the Enter key, it gives the following error.

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

What does this error mean? Why is it occurring? It means that we must have the public class named Test in the Test.java file, but in our case, we have it in the Main.java file.

That’s the only reason for this error. How to fix this? We can get rid of it in the following two ways.

Fix the class X is public, should be declared in a file named X.java Error

Rename the File

To fix this error, rename the file as Test.java, which contains the Test class as given below.

Example Code (Test.java file):

public class Test {
  public static void main(String[] param) {
    HiWorld();
    System.exit(0);
  }

  public static void HiWorld() {
    System.out.println("Hi World");
  }
}

Compile the Code:

javac Test.java

Run the Code:

java Test

OUTPUT:

Hi World

Rename the Class

We can keep the file name as Main.java for the second solution but rename the class as Main. See the code snippet below.

Example Code (Main.java file):

public class Main {
  public static void main(String[] param) {
    HiWorld();
    System.exit(0);
  }

  public static void HiWorld() {
    System.out.println("Hi World");
  }
}

Compile the Code:

javac Main.java

Run the Code:

java Main

OUTPUT:

Hi World
Mehvish Ashiq avatar Mehvish Ashiq avatar

Mehvish Ashiq is a former Java Programmer and a Data Science enthusiast who leverages her expertise to help others to learn and grow by creating interesting, useful, and reader-friendly content in Computer Programming, Data Science, and Technology.

LinkedIn GitHub Facebook

Related Article - Java Error