Java Source File Structure

A Java Program can contain any number of classes but at most one class can be declared as public. If there is a public class the name of the Program and name of the public class must be matched otherwise we will get compile time error”.

If there is no public class then any name we gives for java source file.

class A{ } class B{ } class C{ }

If there is no public class then we can use any name for java source file there are no restrictions

If class B declared as public then the name of the Program should be B.java otherwise we will get compile time error saying “class B is public, should be declared in a file named B.java”.

  • If both B and C classes are declared as public and name of the file is B.java then we will get compile time error saying “class C is public, should be declared in a file named C.java”.
  • It is highly recommended to take only one class for source file and name of the Program (file) must be same as class name. This approach improves readability and understandability of the code