Java Documentation Comments

Java supports three types of comments. The first two are the // and the /* */. The third type is called a documentation comment. It begins with the character sequence /** and it ends with */.
Documentation comments allow you to embed information about your program into the program itself. You can then use the javadoc utility program to extract the information and put it into an HTML file.
Documentation comments make it convenient to document your programs.

The javadoc Tags:

The javadoc utility recognizes the following tags:
TagDescriptionExample
@authorIdentifies the author of a class.@author description
@deprecatedSpecifies that a class or member is deprecated.@deprecated description
{@docRoot}Specifies the path to the root directory of the current documentationDirectory Path
@exceptionIdentifies an exception thrown by a method.@exception exception-name explanation
{@inheritDoc}Inherits a comment from the immediate superclass.Inherits a comment from the immediate surperclass.
{@link}Inserts an in-line link to another topic.{@link name text}
{@linkplain}Inserts an in-line link to another topic, but the link is displayed in a plain-text font.Inserts an in-line link to another topic.
@paramDocuments a method's parameter.@param parameter-name explanation
@returnDocuments a method's return value.@return explanation
@seeSpecifies a link to another topic.@see anchor
@serialDocuments a default serializable field.@serial description
@serialDataDocuments the data written by the writeObject( ) or writeExternal( ) methods@serialData description
@serialFieldDocuments an ObjectStreamField component.@serialField name type description
@sinceStates the release when a specific change was introduced.@since release
@throwsSame as @exception.The @throws tag has the same meaning as the @exception tag.
{@value}Displays the value of a constant, which must be a static field.Displays the value of a constant, which must be a static field.
@versionSpecifies the version of a class.@version info

Documentation Comment:

After the beginning /**, the first line or lines become the main description of your class, variable, or method.
After that, you can include one or more of the various @ tags. Each @ tag must start at the beginning of a new line or follow an asterisk (*) that is at the start of a line.
Multiple tags of the same type should be grouped together. For example, if you have three @see tags, put them one after the other.
Here is an example of a documentation comment for a class:
/**
* This class draws a bar chart.
* @author Zara Ali
* @version 1.2
*/

What javadoc Outputs?

The javadoc program takes as input your Java program's source file and outputs several HTML files that contain the program's documentation.
Information about each class will be in its own HTML file. Java utility javadoc will also output an index and a hierarchy tree. Other HTML files can be generated.
Since different implementations of javadoc may work differently, you will need to check the instructions that accompany your Java development system for details specific to your version.

Example:

Following is a sample program that uses documentation comments. Notice the way each comment immediately precedes the item that it describes.
After being processed by javadoc, the documentation about the SquareNum class will be found in SquareNum.html.
import java.io.*;

/**
* This class demonstrates documentation comments.
* @author Ayan Amhed 
* @version 1.2
*/
public class SquareNum {
   /**
   * This method returns the square of num.
   * This is a multiline description. You can use
   * as many lines as you like.
   * @param num The value to be squared.
   * @return num squared.
   */
   public double square(double num) {
      return num * num;
   }
   /**
   * This method inputs a number from the user.
   * @return The value input as a double.
   * @exception IOException On input error.
   * @see IOException
   */
   public double getNumber() throws IOException {
      InputStreamReader isr = new InputStreamReader(System.in);
      BufferedReader inData = new BufferedReader(isr);
      String str;
      str = inData.readLine();
      return (new Double(str)).doubleValue();
   }
   /**
   * This method demonstrates square().
   * @param args Unused.
   * @return Nothing.
   * @exception IOException On input error.
   * @see IOException
   */
   public static void main(String args[]) throws IOException
   {
      SquareNum ob = new SquareNum();
      double val;
      System.out.println("Enter value to be squared: ");
      val = ob.getNumber();
      val = ob.square(val);
      System.out.println("Squared value is " + val);
   }
}
Now process above SquareNum.java file using javadoc utility as follows:
$ javadoc SquareNum.java
Loading source file SquareNum.java...
Constructing Javadoc information...
Standard Doclet version 1.5.0_13
Building tree for all the packages and classes...
Generating SquareNum.html...
SquareNum.java:39: warning - @return tag cannot be used\
                      in method with void return type.
Generating package-frame.html...
Generating package-summary.html...
Generating package-tree.html...
Generating constant-values.html...
Building index for all the packages and classes...
Generating overview-tree.html...
Generating index-all.html...
Generating deprecated-list.html...
Building index for all classes...
Generating allclasses-frame.html...
Generating allclasses-noframe.html...
Generating index.html...
Generating help-doc.html...
Generating stylesheet.css...
1 warning
$

Java - Generics

It would be nice if we could write a single sort method that could sort the elements in an Integer array, a String array or an array of any type that supports ordering.
Java Generic methods and generic classes enable programmers to specify, with a single method declaration, a set of related methods or, with a single class declaration, a set of related types, respectively.
Generics also provide compile-time type safety that allows programmers to catch invalid types at compile time.
Using Java Generic concept we might write a generic method for sorting an array of objects, then invoke the generic method with Integer arrays, Double arrays, String arrays and so on, to sort the array elements.

Generic Methods:

You can write a single generic method declaration that can be called with arguments of different types. Based on the types of the arguments passed to the generic method, the compiler handles each method call appropriately. Following are the rules to define Generic Methods:
  • All generic method declarations have a type parameter section delimited by angle brackets (< and >) that precedes the method's return type ( < E > in the next example).
  • Each type parameter section contains one or more type parameters separated by commas. A type parameter, also known as a type variable, is an identifier that specifies a generic type name.
  • The type parameters can be used to declare the return type and act as placeholders for the types of the arguments passed to the generic method, which are known as actual type arguments.
  • A generic method's body is declared like that of any other method. Note that type parameters can represent only reference types not primitive types (like int, double and char).

Example:

Following example illustrate how we can print array of different type using a single Generic method:
public class GenericMethodTest
{
   // generic method printArray                         
   public static < E > void printArray( E[] inputArray )
   {
      // Display array elements              
         for ( E element : inputArray ){        
            System.out.printf( "%s ", element );
         }
         System.out.println();
    }

    public static void main( String args[] )
    {
        // Create arrays of Integer, Double and Character
        Integer[] intArray = { 1, 2, 3, 4, 5 };
        Double[] doubleArray = { 1.1, 2.2, 3.3, 4.4 };
        Character[] charArray = { 'H', 'E', 'L', 'L', 'O' };

        System.out.println( "Array integerArray contains:" );
        printArray( intArray  ); // pass an Integer array

        System.out.println( "\nArray doubleArray contains:" );
        printArray( doubleArray ); // pass a Double array

        System.out.println( "\nArray characterArray contains:" );
        printArray( charArray ); // pass a Character array
    } 
}
This would produce following result:
Array integerArray contains:
1 2 3 4 5 6

Array doubleArray contains:
1.1 2.2 3.3 4.4 

Array characterArray contains:
H E L L O

Bounded Type Parameters:

There may be times when you'll want to restrict the kinds of types that are allowed to be passed to a type parameter. For example, a method that operates on numbers might only want to accept instances of Number or its subclasses. This is what bounded type parameters are for.
To declare a bounded type parameter, list the type parameter's name, followed by the extends keyword, followed by its upper bound.

Example:

Following example illustrate how extends is used in a general sense to mean either "extends" (as in classes) or "implements" (as in interfaces). This example is Generic method to return the largest of three Comparable objects:
public class MaximumTest
{
   // determines the largest of three Comparable objects
   public static <T extends Comparable<T>> T maximum(T x, T y, T z)
   {                      
      T max = x; // assume x is initially the largest       
      if ( y.compareTo( max ) > 0 ){
         max = y; // y is the largest so far
      }
      if ( z.compareTo( max ) > 0 ){
         max = z; // z is the largest now                 
      }
      return max; // returns the largest object   
   }
   public static void main( String args[] )
   {
      System.out.printf( "Max of %d, %d and %d is %d\n\n", 
                   3, 4, 5, maximum( 3, 4, 5 ) );

      System.out.printf( "Maxm of %.1f,%.1f and %.1f is %.1f\n\n",
                   6.6, 8.8, 7.7, maximum( 6.6, 8.8, 7.7 ) );

      System.out.printf( "Max of %s, %s and %s is %s\n","pear",
         "apple", "orange", maximum( "pear", "apple", "orange" ) );
   }
}
This would produce following result:
Maximum of 3, 4 and 5 is 5

Maximum of 6.6, 8.8 and 7.7 is 8.8

Maximum of pear, apple and orange is pear

Generic Classes:

A generic class declaration looks like a non-generic class declaration, except that the class name is followed by a type parameter section.
As with generic methods, the type parameter section of a generic class can have one or more type parameters separated by commas. These classes are known as parameterized classes or parameterized types because they accept one or more parameters.

Example:

Following example illustrate how we can define a generic class:
public class Box<T> {

  private T t;

  public void add(T t) {
    this.t = t;
  }

  public T get() {
    return t;
  }

  public static void main(String[] args) {
     Box<Integer> integerBox = new Box<Integer>();
     Box<String> stringBox = new Box<String>();
    
     integerBox.add(new Integer(10));
     stringBox.add(new String("Hello World"));

     System.out.printf("Integer Value :%d\n\n", integerBox.get());
     System.out.printf("String Value :%s\n", stringBox.get());
  }
}
This would produce following result:
Integer Value :10

String Value :Hello World

Java - Data Structures

The data structures provided by the Java utility package are very powerful and perform a wide range of functions. These data structures consist of the following interface and classes:
  • Enumeration
  • BitSet
  • Vector
  • Stack
  • Dictionary
  • Hashtable
  • Properties
All these classes are now legacy and Java-2 has introduced a new framework called Collections Framework which is discussed in next tutorial:

The Enumeration:

The Enumeration interface isn't itself a data structure, but it is very important within the context of other data structures. The Enumeration interface defines a means to retrieve successive elements from a data structure.
For example, Enumeration defines a method called nextElement that is used to get the next element in a data structure that contains multiple elements.
To have more detail about this interface, check The Enumeration.

The BitSet

The BitSet class implements a group of bits, or flags, that can be set and cleared individually.
This class is very useful in cases where you need to keep up with a set of boolean values; you just assign a bit to each value and set or clear it as appropriate.
To have more detail about this class, check The BitSet.

The Vector

The Vector class is similar to a traditional Java array, except that it can grow as necessary to accommodate new elements.
Like an array, elements of a Vector object can be accessed via an index into the vector.
The nice thing about using the Vector class is that you don't have to worry about setting it to a specific size upon creation; it shrinks and grows automatically when necessary.
To have more detail about this class, check The Vector.

The Stack

The Stack class implements a last-in-first-out (LIFO) stack of elements.
You can think of a stack literally as a vertical stack of objects; when you add a new element, it gets stacked on top of the others.
When you pull an element off the stack, it comes off the top. In other words, the last element you added to the stack is the first one to come back off.
To have more detail about this class, check The Stack.

The Dictionary

The Dictionary class is an abstract class that defines a data structure for mapping keys to values.
This is useful in cases where you want to be able to access data via a particular key rather than an integer index.
Since the Dictionary class is abstract, it provides only the framework for a key-mapped data structure rather than a specific implementation.
To have more detail about this class, check The Dictionary.

The Hashtable

The Hashtable class provides a means of organizing data based on some user-defined key structure.
For example, in an address list hash table you could store and sort data based on a key such as ZIP code rather than on a person's name.
The specific meaning of keys in regard to hash tables is totally dependent on the usage of the hash table and the data it contains.
To have more detail about this class, check The Hashtable.

The Properties

Properties is a subclass of Hashtable. It is used to maintain lists of values in which the key is a String and the value is also a String.
The Properties class is used by many other Java classes. For example, it is the type of object returned by System.getProperties( ) when obtaining environmental values.
To have more detail about this class, check The Properties.

Simple DateFormat format codes:

CharacterDescriptionExample
GEra designatorAD
yYear in four digits2001
MMonth in yearJuly or 07
dDay in month10
hHour in A.M./P.M. (1~12)12
HHour in day (0~23)22
mMinute in hour30
sSecond in minute55
SMillisecond234
EDay in weekTuesday
DDay in year360
FDay of week in month2 (second Wed. in July)
wWeek in year40
WWeek in month1
aA.M./P.M. markerPM
kHour in day (1~24)24
KHour in A.M./P.M. (0~11)10
zTime zoneEastern Standard Time
'Escape for textDelimiter
"Single quote`

Date and Time Conversion Characters:

CharacterDescriptionExample
cComplete date and timeMon May 04 09:51:52 CDT 2009
FISO 8601 date2004-02-09
DU.S. formatted date (month/day/year)02/09/2004
T24-hour time18:05:19
r12-hour time06:05:19 pm
R24-hour time, no seconds18:05
YFour-digit year (with leading zeroes)2004
yLast two digits of the year (with leading zeroes)04
CFirst two digits of the year (with leading zeroes)20
BFull month nameFebruary
bAbbreviated month nameFeb
nTwo-digit month (with leading zeroes)02
dTwo-digit day (with leading zeroes)03
eTwo-digit day (without leading zeroes)9
AFull weekday nameMonday
aAbbreviated weekday nameMon
jThree-digit day of year (with leading zeroes)069
HTwo-digit hour (with leading zeroes), between 00 and 2318
kTwo-digit hour (without leading zeroes), between 0 and 2318
ITwo-digit hour (with leading zeroes), between 01 and 1206
lTwo-digit hour (without leading zeroes), between 1 and 126
MTwo-digit minutes (with leading zeroes)05
STwo-digit seconds (with leading zeroes)19
LThree-digit milliseconds (with leading zeroes)047
NNine-digit nanoseconds (with leading zeroes)047000000
PUppercase morning or afternoon markerPM
pLowercase morning or afternoon markerpm
zRFC 822 numeric offset from GMT-0800
ZTime zonePST
sSeconds since 1970-01-01 00:00:00 GMT1078884319
QMilliseconds since 1970-01-01 00:00:00 GMT1078884319047

Counters