Style Guide For Java Programmers

Comments

Javadoc comment for a class

Every class should have a Javadoc comment in front of the class declaration, indicating the purpose of the class, the author, the date, version number if appropriate, any revisions (modifications) made to the class and the dates of revision. For a submitted assignment version numbers and revisions can be omitted but it is important to include your name, student number, assignment number and purpose of the class. Here is an example Javadoc comment for a class submitted as an assignment (you can also use the @author and @version Javadoc tags).

/**
 * TITLE: Solution to Assignment 0, COSC 1046, Due Oct. 2, 2017
 * <p>
 * PURPOSE: An object of this class can determine the minimum number
 *    of dollars, quarters, dimes, nickels, and cents a customer should
 *    receive as change given the amount due and the amount received by
 *    the customer. These given amounts are double numbers of the form
 *    x.xx
 * <p>
 * AUTHOR: Fred G. Smith
 * <p>
 * DATE: October 1, 2003
 * <p>
 * STUDENT NUMBER: 4564964565
 */
public class ChangeHelper
{
   ...
}

WARNING: There should be no lines other than blank lines beteen this Javadoc comment and the class declaration.

NOTE: Javadoc produces HTML documentation so the <p> tags are needed to begin a new paragraph.

Javadoc comment for a method

In front of each public method in a class you should include a Javadoc comment that summarizes the purpose of the method. If the method has parameters include a Javadoc @param tag for each parameter. If the method returns a value include a Javadoc @return tag. Here is an example.

/**
 * Compute the sum of two integers.  
 * @param a the first integer
 * @param b the second integer
 * @return the sum of a and b
 */
 public int add(int a, int b)
 {
    ...
 }

When we write methods that throw exceptions we will also use the Javadoc @throws tag.

Block comments

Block comments are also used to explain a block of statements. There are two common styles:
/* The following loop counts from 1 to 100
   in steps of 5 and displays the counter
*/
or
// The following loop counts from 1 to 100
// in steps of 5 and displays the counter
Pick one. It is easier to edit the comment if the first style is used.

End of line comments

They appear at the end of a statement after the semi-colon. For example,
int total; // total change in pennies
Make comments meaningful. For example, never do the following
count = count + 1; // add 1 to count
which just echoes the code.

Line spacing and whitespace

Use blank lines to visually separate a group of related statements. In expressions leave a space on either side of a binary + or - operator, or the assignment operator. For example,
r =  (-b + Math.sqrt(b * b - 4 * a * c)) / (2*a);
Alternatively use spaces to separate terms and no spaces to separate factors as in
r = (-b + Math.sqrt(b*b - 4*a*c)) / (2*a);
In any case the following should be avoided.
r=(-b+Math.sqrt(b*b-4*a*c))/(2*a);

Naming Conventions For Identifiers

Names that you define or use in a Java class are either keywords (names such as int or double) or user defined identifiers such as numberOfMarks, System, or KeyboardReader. Lowercase letters are used for keywords and the following conventions are used for user-defined identifiers.

NOTE: The following naming conventions are not enforced by the compiler. However, they are almost a universal convention.

Variable names

Use meaningful variable names. Don't worry about the extra typing needed for long names. Readability is very important. Here are the standard rules.

Class names

Constant names

Block structure and indentation

When writing classes and methods, if statements, and while, for and do-while loops there are three common styles for aligning the braces that define a block. We can illustrate them with an if statement.

(a)   if (........)   (b)  if (........)    (c)  if (........) {
      {                    {  statement;            statement;
         statement;           statement;            statement;
         statement;           .....                 .....
         .....             }                     }
      }

Style (a) is recommended. We suggest that you use either (a) or (b) since the brackets can be visually aligned. Consistency of form is important -- choose one style and stick with it. Style (c) is not recommended although it is popular since the braces cannot be visually aligned.

Similar styles can be used for the for, while and do-while loops.

Also use a consistent indentation. An indentation of 2 to 4 is best. We recommend 3 spaces. Larger indentations tend to make your code walk off the right side of the page, especially if nested structures are used. Also you should never use tabs for indentation unless you set your editor to convert tabs to the appropriate number of spaces when saving or printing a file.

Single line blocks

For the if statement and the various loop statements, if the block contains only a single statement the braces can be omitted. Thus you can write any of the following three statements

(a)   if (.....)      (b)  if (.....)      (c)  if (.....) statement;
         statement;        {                     
                              statement; 
                           }

Again, pick a style and stick with it. Style (c) is often called the single line if statement. If you use style (b) (recommended) you will make fewer programming errors.

An example class

/**
 * TITLE: Solution to Assignment 4, COSC 1046, October 2, 2017<br>
 * PURPOSE:This program verifies one of deMorgan's laws.
 * In Java the law is
 * <pre>
 *    ! (p || q) = (!p) && (!q)
 * </pre>
 * The program calculates the left hand side and compares
 * it with the right hand side and illustrates doubly nested
 * for loops with if statements in the inner loop.
 * <p>
 * AUTHOR: Mark Allan White<br>
 * DATE: October 16, 1999<br>
 * STUDENT NUMBER: 4584567565
 * </p>
 */
public class DeMorgan
{
   /** Construct an object
    */
   public DeMorgan()
   {
   }
   /**
    * Do the test to verify deMorgan's law
    */
   public void doTest()
   {
      // Initialize outer loop with a false value of p.

      boolean p = false;
      for (int i = 0; i <= 1; i++)
      {
         // Initialize inner loop with a false value of q.

         boolean q = false;
         for (int j = 0; j <= 1; j++)
         {
            // Compute left and right hand sides of deMorgan's law.

            boolean lhs = ! (p || q);
            boolean rhs = (! p) && (! q);

            // Display lhs and rhs as a row of the table

            if (lhs == true)
               System.out.print("true ");
            else
               System.out.print("false");

            System.out.print("  "); // 2 spaces between row entries

            if (rhs == true)
               System.out.print("true ");
            else
               System.out.print("false");

            System.out.println();

            // change q to true for 2nd time through inner loop

            q = ! q;
         } // end for

         // Change p to true for 2nd time through outer loop

         p = ! p;
      } // end for
   } // end doTest
}

Here we have shown how to use a comment to identify the structure that a closing brace is ending. This can be useful in nested structures that may be too long for the braces to be visually alligned.