Wednesday, December 7, 2011

Source File Declaration Rules in Java


C:\folder>javac test.java
test.java:9: class Test is public, should be declared in a file named Test.java
public class test
       ^
1 error

The above error appeared because the source file declaration rules in java says that If there is a public class in a file, the name of the file must match the name of the public class. For example, a class declared as public class Test { } must be in a source code file named Test.java. Also note that in Java everything is case-sensitive hence test and Test are treated as two different things.

Below are the rules associated with declaring classes, import statements, and package statements in a source file.

  • There can be only one public class per source code file.
  • Comments can appear at the beginning or end of any line in the source code file; they are independent of any of the positioning rules discussed here.
  • If there is a public class in a file, the name of the file must match the name of the public class. For example, a class declared as public class Test { } must be in a source code file named Test.java.
  • If the class is part of a package, the package statement must be the first line in the source code file, before any import statements that may be present.
  • If there are import statements, they must go between the package statement (if there is one) and the class declaration. If there isn't a package statement, then the import statement(s) must be the first line(s) in the source code file. If there are no package or import statements, the class declaration must be the first line in the source code file.
  • import and package statements apply to all classes within a source code file. In other words, there's no way to declare multiple classes in a file and have them in different packages, or use different imports.
  • A file can have more than one nonpublic class.
  • Files with no public classes can have a name that does not match any of the classes in the file