J2EEOnline J2EE






Java Fundamentals  «Prev  Next»
Lesson 2Source files and compilation units
Objective Relationship between Java programs, source files, and compilation units
Source Code Files

Source Files and compilation units

Describe the relationship between Java programs, source files, and compilation units.
You write Java programs by declaring classes and interfaces in source code files, referred to as compilation units.
Classes are the cornerstone of Java programs. They declare variables, methods, and constructors .
  1. Variables are used to store the values of primitive types and provide references to objects .
  2. Methods are used to access variables and perform operations on them.
  3. Constructors are used to create objects, which are instances of classes.
Interfaces define constants and methods. For a class to implement a particular interface, it must implement all of the methods that are defined in the interface. A class can define any constant whether or not the constants are already defined in the interfaces implemented by the class.

The structure of Java programs
The figure below describes the concept of compilation units.



Java Compilation Unit

It is basically referred to a Java source code file, which forms the input for the Java compiler which is javac. This term is less commonly used among developers and it is technical jargon for Java source code file. This Java compilation unit has structure which is as follows
[ package declaration ] 
[ import declararion/s or static import declaration/s]
[ top-level type declaration/s; ]

Some points about the compilation unit, these are somewhat based on compiler:
  1. may or may not contain the above components
  2. if anyone of them present, then must go in selected slots and follow order as shown above, such as, package declaration should be before any of type declaration
  3. can contain the one or more type declaration must go in the order as shown above, type in this case can be class, interface, enum or annotation
  4. if it contains public access level type then it must be only one and can have no. of non-public/default level types, In other words, it can contain '1' public type and any 'n' non-public types
  5. name of compilation unit can be, name of the public type, if present or any type name inside it or anything you like provided no public type are present inside it
  6. non-javadoc comments can go anywhere, does not necessary follow any order as shown above structure.
Java source code files end with the .java extension and contain at least one class or interface declaration. A source code file may declare, at most, one public class or interface. If a source code file declares a public class or interface, the file's name must match that of the class or interface.