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-
- may or may not contain the above components
- 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
- 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
- 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
- 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
- non-javadoc comments can go anywhere, does not necessary follow any order as shown above structure.
Following code listing contains sample Java compilation
This should be named MyClass.java
// compilation unit package declaration package compilation.unit.one; // import declaration goes here import java.util.ArrayList; import java.util.List; import static java.lang.Math.random; import static java.lang.System.out; // rest of the compilation unit has type declarations // a class declaration which is public and compilation unit carries this name public class MyClass { public static void main(String[] args) { List<String> list = new ArrayList<String>(); list.add("One"); // static import for out out.println(list); // static import for random mehod double random = random(); out.println(random); } } // interface declaration interface Actions { void doStuff(); } // enums declaration enum State { ONE, TWO } // annotations declaration @interface Annotate { } // end of compilation unit
Hi ,
Great blog! Is there an email address I could contact you in private?
thanks !!
Thank u 🙂 this was my interview question which i didnt answer