Java Compilation error – public, should be declared in a file named

When you compile a Java class with name of the public class not matching the source code file name then you would receive compilation error “public, should be declared in a file”.

In the following example, we have the public class name as Test1 but this has been saved as Test.java.

public class Test1 {

public static void main(String args[]) {

System.out.println("Hello !!!");

}

}

C:ProjectsJavamyscjpchap1>javac Test.java

Test.java:1: class Test1 is public, should be declared in a file named Test1.java

public class Test1 {

^

1 error

In Category: Java, SCJP

Ravi Shankar

A Software developer and blogger who is always looking to provide technical help to the wider community.

Show 0 Comments
No comments yet. Be the first.

Leave a Comment

Get your free copies of the following tech guides by joining the Digital Answers mailing list.