What is legal Java? — Program files

The top-level

In Java a file is called a compilation unit. This is the file whose names ends in .java that is processed by javac, the Java compiler.

Java’s legal defintion of a compilation Unit states that it is a series of three optional components.

  1. a single package declaration
  2. a series of import declarations
  3. a series of type declaratsions

We’ll look at these individually while ignoring some aspects of Java, such as annotations, for a bit later in the course.

Package declaration

The package declaration, which should be present in all your Java programs, is a one line statement that associates your program with a package. In class assignments, you’ll usually be given a specific package name to use.

Here’s an example of a package declaration.

package edu.unca.cs.csci202.home1 ;

Import declaration

Import declarations allows important Java classes to be accessed without using the long package name. For example, you can say Scanner rather than java.util.Scanner or say Enchantment rather than say org.bukkit.enchantments.Enchantment.

There are four types of import declarations. For now we will ignore the static import added in Java 5. The two import statements you are likely to use are the single-type import which imports and single class and the type-intput-on-demand which uses a wildcard to import classes that start with a common package prefix.

In the Spring 2012 semester, this is the import declarations sections more frequently used by CSCI 202 students.

import java.util.* ;

The way, the * in a type-import-on-demand only matches one identifier. Consequently, the above import will not match the java.util.concurrent.BlockingDeque interface.

Some people prefer explicit lists of imported class. Here are a couple of import statements that were also seen in CSCI 202.

import java.util.Deque;
import java.util.LinkedList;

Type declarations

The type declarations are definitions of Java classes and interfaces. Only one of there definitions can be public. The Java coding conventions state that the public class should be the first one defined in the file.

In any case, class and interface declarations do need at least an entire web page.