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.

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

About these ads

3 thoughts on “Java Compilation Unit

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s