Rules for Declaring a Source File in Java

Rules for Declaring a Source File in Java

by | 21-Mar-2020



  1. The file name can be anything but the extension must be java.
  2. Within one source file, any number of custom type(s) i.e. class, interface, enum, and annotation can be defined.
  3. A file name can be anything if there isn't any public custom type (class, interface, enum, annotation).
  4. If there is a public custom type then the source file name must be the same as the public custom type name.
  5. Within one source file, there can be only one public custom type. If required, any number of non-public types can be defined.
  6. If there are multiple custom types within a source file then for every custom type separate class file will be generated.
  7. All the classes defined in a source code file can have the main method.
  8. At the time of execution, the class name must be specified with the java interpreter. If the specified class has the main method then it will be executed otherwise an error message will be displayed.
  9. At the time of compilation, the compiler will check for syntax error(s) in the source file. If there is any syntax error then none of the class file(s) will be generated.
  10. If no syntax error is found then the compiler will verify grammatical rules for the individual types from the first custom type. If there is no grammatical error then only the class will be generated and the next class will be verified.
  11. The following command can be used to verify the task of the compiler:

javac –verbose <file name>.java 

  1. In a source file, a package statement must be the first statement, if any.
  2. Import statements must come after package statement (if available) and before the first custom type is declared.
  3. There can any number of import statement(s) in a source file.
  4. Package and import statement(s) will be used for all the types declared in the source file.


There are no comments.

Enter a new Comment:

Copyright Šprgrmmng. All rights reserved.