What are Java source file declaration rules?

A Java source file is a plain text file containing Java source code and having .java extension. The .java extension means that the file is the Java source file. Java source code file contains source code for a class, interface, enumeration, or annotation type. There are some rules associated to Java source file. We should adhere to following rules while writing Java source code.

  • 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. Java comment can be inserted anywhere in a program code where a white space can be
  • 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 Dog { } must be in a source code file named Dog.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 non~public class.
  • Files with non~public classes can have a name that does not match any of the classes in the file

Hope you have enjoyed reading Java source file declaration rules. Please do write us if you have any suggestion/comment or come across any error on this page. Thanks for reading!




Get Free Tutorials by Email

About the Author

is the main author for cs-fundamentals.com. He is a software professional (post graduated from BITS-Pilani) and loves writing technical articles on programming and data structures.

Today's Tech News

AlphaBay and Hansa dark web markets shut downPosted on Thursday July 20, 2017

The AlphaBay and Hansa marketplaces were known for trade in drugs, weapons and malware.

Kodi magazine 'directs readers to pirate content'Posted on Thursday July 20, 2017

The guide is being investigated by the Federation Against Copyright Theft.

Bitcoin swings as civil war loomsPosted on Thursday July 20, 2017

The Bitcoin community must agree how to tackle a slowdown in transaction times to avoid a schism.

Courtesy BBC News

AD BLOCKER DETECTED!

Advertisements help running this site for free.


To view the content please disable AdBlocker and refresh the page.

×