How to Fix Class X Is Public Should Be Declared in a File Named X.java Error
-
Cause of the
class X is public, should be declared in a file named X.javaError -
Fix the
class X is public, should be declared in a file named X.javaError
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
Related Article - Java Error
- How to Fix the Error: Failed to Create the Java Virtual Machine
- How to Fix the Missing Server JVM Error in Java
- How to Fix the 'No Java Virtual Machine Was Found' Error in Eclipse
- How to Fix Javax.Net.SSL.SSLHandShakeException: Remote Host Closed Connection During Handshake
- How to Fix the Error: Failed to Create the Java Virtual Machine
- How to Fix Java.Lang.VerifyError: Bad Type on Operand Stack
