Java Code Formatter

CodeMorph

CodeToHtml

Coding Standards

Java Coding Standard


You can read and download this Java coding standard, coding style guide, code convention and code guideline from here for free at your own risk. All trademarks, registered trademarks, product names and company names or logos mentioned herein are the property of their respective owners.

Java Coding Standard

Last modified:  Wednesday, September 6, 2000
The Computer Science Department at RIT follows the Coding Conventions for the Java Programming Language, published by Sun Microsystems, with local modifications as listed below:
 
Java Source Files  Each Java source file contains a single public class or interface. The root name of the file will be the name of the public class that it contains, the suffix will be .java.

Any non-public classes in the source file must provide services that are used directly by the public class (such non-public classes may also be used by other public classes in the same package).

All Java Source files must begin with a C-style comment that lists the file name and version information: 

/*
 * filename.java
 *
 * Version:
 *    $Id$
 *
 * Revisions:
 *    $Log$
 */
Line Length
Lines in a source file must never have more than 80 characters.

When a complete statement or an expression will not fit on a single line, break it according to these general principles: 

  1. Break after a comma. 
  2. Break before an operator. 
  3. Prefer higher-level breaks to lower-level breaks. 
  4. Align the new line with the beginning of the expression at the same level on the previous line. 
  5. If the above rules lead to confusing code or to code that's squished up against the right margin, just indent one additional level instead. 
Comments
The comments in your program files are very important aids for assisting programmers who are trying to understand your programs.  There are several categories of comments that you must provide.  The style guidelines for these comments generally follow the JavaDoc commenting standards ( Sun's conventions and guidelines for writing JavaDoc comments).  Writing comments in this format allows for the automatic creation of web pages that describe your programs.
Javadoc
Comments
These are important additional comments that will be displayed in the Javadoc output.

A documentation comment is made up of two parts -- a description followed by zero or more tags, with a blank line (containing a single asterisk "*") between these two sections: 

    /** 
     * This is the description part of a doc comment
     *
     * @tag    Comment for the tag
     */
  • The first line is indented to line up with the code below the comment, and starts with the begin-comment symbol (/**) followed by a return. 
  • Subsequent lines start with an asterisk *. They are indented an additional space so the asterisks line up. A space separates the asterisk from the descriptive text or tag that follows it. 
  • Insert a blank comment line between the description and the list of tags, as shown. 
  • Insert additional blank lines to create "blocks" of related tags. 
  • The last line begins with the end-comment symbol (*/) indented so the asterisks line up and followed by a return. Note that the end-comment symbol contains only a single asterisk (*). 
  • A blank line should precede and follow the comment block.
Class 
Definitions
The following comments will appear before the definition of every class: 
/**
 * A description of what the class does.
 *
 * @author      Author name
 * @author      Contributor 1
 * @author      Contributor 2
                .
                .
 * @author      Contributor n
 */
The elements of a class or interface declaration should appear in the following order:
  1. Class (static) variables 
  2. Instance variables 
  3. Constructors 
  4. Methods 
Public variables should be listed first, followed by protected, then package level (no access modifier), and finally the private variables.  Methods should be grouped by functionality.
Method 
Headers
The following comments will appear before every method (including main): 
    /**
     * A description of what the method does
     *
     * @param       name    description
     * @param       name    description
                    .
                    .
     * @param       name    description
     *
     * @return              description
     *
     * @exception   name    description
     * @exception   name    description
                     .
                     .
     * @exception   name    description
     */
    
    
@param 
The @param tag is followed by the name (not type) of the parameter, followed by a description of the parameter. Additional spaces should be inserted between the name and description so that comments line up in a block. Dashes or other punctuation should not be inserted before the description. The name and data type always start with a lowercase letter. The description is most usually a phrase, starting with a lowercase letter and ending without a period, unless it contains a complete sentence. 
@return 
The @return tag is followed by a description of the return value. Whenever possible, detailed information (such as returns -1 when an out-of-bounds argument is supplied) should be provided. Spaces should be used to line the description up with the rest of the comments in the method. 
@exception 
An @exception tag should be included for at least any declared (checked) exceptions. It can also document any non-declared exceptions that can be thrown by the method, (normally those that appear directly in the implementation, rather than those that are indirectly thrown). 
Declaration and Code Comments In addition to the class and method headers, which describe your class and its interface for a user or client of the class, you must provide additional comments to describe the program code that you have written.  Programmers who must modify your code at some point will use these comments to quickly understand the logic and operations performed.  Someone reading one of your methods should not be required to read actual program statements to gain an understanding of the logic and operations performed in the method.  You must write additional comments that provide this information.

Any non-trivial method (i.e.it is longer than five lines of code) requires comments.  Multiple comments may be needed to adequately describe the method.

  • All code and declaration comments will be started with the "//" (double slash).
  • If the comment requires multiple lines each will be started with the "//".
  • Declaration comments provide a description of the data object declared.
    •  
    • They can appear at the end of the declaration line provided the comment does not extend the line beyond 80 characters; otherwise, they appear preceeding the declaration and indented at the same level as the declaration with a blank line preceeding the comment.
    • If there are multiple declaration lines in a row all comments will start in the same column.

    •  
  • A comment for code appears on a line by itself preceding the code to which it refers.
  • A blank line will precede the comment and for clarity, a blank line can also optionally follow the comment.
  • The indentation will match the code following the comment line(s).
Note: these declaration and comments will not appear in the web-based documentation generated by Javadoc.
Identifiers  Class names begin with a capital letter; method and variable names begin with a lowercase letter. The remaining letters are lowercase.  The second and subsequent words of multi-word identifiers are also capitalized, but not separated by underscores. 

Constants are given names to indicate their use and meaning. These names will be all upper case letters. The words of multi-word identifiers are separated from one another by underscores ("_"). 

Indenting  The indentation of your program code provides a strong visual indication of the structure of your methods.  This greatly aids in understanding the code.  Consistency is the most important characteristic of indenting style.  It is recommended that you use an indent no smaller than 2 and no larger than 8 spaces. Tabs must not be used to indent since different editors treat tabs in diferent ways. 

When using braces ( "{" or "}" ) in a Java program, you must follow the "standard Java" style as found in Sun's sources: 

  • The opening brace should be at the end of the line that begins the compound statement or declaration; the closing brace should begin a line and be indented to the same level as the line holding the opening brace. 
  • The enclosed statements should be indented one more level than the lines containing the opening and closing braces.
  • Braces are used around all statements, even single statements, when they are part of a control structure, such as a if-else or for statement. This makes it easier to add statements without accidentally introducing bugs due to forgetting to add braces. 
Horizontal 
Spacing
Like indentation, consistent spacing around special characters aids in the understanding of your program code.  A suggested style for horizontal spacing is:
  • When using parenthesis to delimit argument lists, there should be no space before the left parenthesis ('('), one space after it, and one space before the right (')') parenthesis.  For empty argument lists no spaces are placed between the parentheses.
  • Commas should always be followed by a space, but never preceded by one.
  • Parenthesis in expressions should have a space both before and after.
  • Binary operators should be surrounded by a space on each side; no space separates an unary operator from its operand.
  • There will always be at least one blank line between the end of a method definition and the method header for the following method. 
Example
Program
/*
 * ConversionTable.java
 *
 * Version:
 *    $Id$
 *
 * Revisions:
 *    $Log$
 */
// Import statements are placed here

 
/**
 * This program produces a conversion table from Celsius to
 * Fahrenheit for values from 0 to 99.  This program appears in
 * "Java Gently" by J M Bishop.
 *
 * @author      J M Bishop
 * @author      Paul Tymann
 */

class ConversionTable {
  static final int    COLS_PER_LINE = 5;    // number of temp. cols
  static final int    MAX_LINE_NO = 20;     // number of rows of temp.
  static final String GAP = "\t";           // white space between cols

  /**
   * The main program.
   *
   * @param    args    command line arguments (ignored)
   */

  public static void main( String [] args ) {
    // print out the table heading
    System.out.println( "\t\tTemperature Conversion Table" );
    System.out.println( "\t\t============================" );
    System.out.println();

    // print a heading for each column of output

    for ( int col = 0; col < COLS_PER_LINE; col++ ) {
      System.out.print( "C  F" + GAP );
    }

    System.out.println();

    // print out the lines of the table

    for ( int row = 0; row < MAX_LINE_NO; row++ ) {
      printRow( row );
    }
  }

  /**
   * Given the row, calculate the Celsius values for the line
   * and display them with their Fahrenheit equivalents.
   *
   * @param    row    row to print
   */

  static void printRow( int row ) {
    for ( int col = 0; col < COLS_PER_LINE; col++ ) {
      int degCelsius = row * COLS_PER_LINE + col;

      System.out.print( degCelsius + " " );
      System.out.print( fahrenheit( degCelsius ) + GAP );
    }

    System.out.println();
  }

  /**
   * Convert degrees Celsius to degrees Fahrenheit
   *
   * @param    celsius    degrees in Celsius
   *
   * @return              degrees in Fahrenheit
   */

  static int fahrenheit( int celsius ) {
    return Math.round( celsius * 9 / 5 + 32 );
  }

} // ConversionTable
Example
Statements
Switch Statement:
char letter = 'B';
double grade;

switch ( letter ) {
case 'A':
case 'a':
  grade = 4.0;
  break;
case 'B':
case 'b':
  grade = 3.0; 
  break;
case 'C':
case 'c':
  grade = 2.0;
  break;
case 'D':
case 'd':
  grade = 1.0;
  break;
default: 
  grade = 0;
  break;
}

While Statement:
int number = 1;
int sum = 0;

while ( number < 100 ) {
  sum = sum + number;
  number++;
}

Do While Statement:
int sum = 0; 
int number = 1;

do {
  sum += number;
  number++;
} while ( number < 100 );

If, if-else, if else-if else Statements:
int number = 1;

if ( number < 100 ) {
  number = number + 100;
}

if ( number < 100 ) {
  number = number + 100;
} else {
  number = number * 10;
}

if ( number < 100 ) {
  number = number + 100;
} else if ( number > 100 ) {
  number = number * 10;
} else {
  number = number / 2;
}

  Format Java source code by hand?  Try SourceFormatX Java Code Formatter today to let it format all java code for you!