Java Coding Style Guidelines
Adapted with permission from JAVA CODE CONVENTIONS. Copyright 1995-1999 Sun Microsysytems, Inc. All rights reserved. http://java.sun.com/docs/codeconv/
Adapted to adhere to CS Department faculty style recommendations, December 2011.

 

1 Why Have Code Conventions
Code conventions are important to programmers for a number of reasons:

  • 80% of the lifetime cost of a piece of software goes to maintenance.
  • Hardly any software is maintained for its whole life by the original author.
  • Code conventions improve the readability of the software, allowing engineers to understand new code more quickly and thoroughly.
  • If you ship your source code as a product, you need to make sure it is as well packaged and clean as any other product you create. For the conventions to work, every person writing software must conform to the code conventions. Everyone.
  • Coding standards ARE used in "the real world" and so it is a vital part of a student's training for this to become second nature.
2 Automated Style Checkers
2.1 BlueJ
2.2 Eclipse
2.3 Command-line (student2.cs.appstate.edu)
2.4 Web-based checker
3 File Organization
3.1 Java Source Files
3.2 README Information File
4 Indentation
4.1 Line Length
4.2 Wrapping Lines
5 Comments
5.1 Documentation Comments
    5.1.1 File Level
    5.1.2 Class Level
    5.1.3 Method Level
5.2 Implementation Comments
    5.2.1 Block Comments
    5.2.2 Single-Line Comments
    5.2.3 Trailing Comments
6 Declarations
6.1 Number Per Line
6.2 Initialization
6.3 Placement
6.4 Class and Method Declarations
7 Statements
7.1 Simple Statements
7.2 Compound Statements
7.3 return Statements
7.4 if, if-else, if else-if else Statements
7.5 for Statements
7.6 while Statements
7.7 do-while Statements
7.8 switch Statements
7.9 try-catch Statements
8 White Space
8.1 Blank Lines
8.2 Blank Spaces
9 Naming Conventions
10 Programming Practices
10.1 Providing Access to Instance and Class Variables
10.2 Magic Number Constants
10.3 Parentheses
10.4 Returning Boolean Constants
10.5 Code Duplication
10.6 Breaking long lines
11 Examples
11.1 Good example
11.2 Bad example
11.3 Bad example checkstyle results

 
 
 
 

2.1 BlueJ

An extension to the
BlueJ development environment provides style checking. Here's what you need to do:
  1. See if the extension is installed already.
  2. If it is NOT installed then you need to copy a file into a specific directory.
  3. Once the extension is installed, you need to configure it to check style according to our style guide.
  4. To use the checker, select the BlueJ Tools menu option and then select Checkstyle.
[BACK TO TOP]  
 
 

2.2 Eclipse

There is a plug-in for the Eclipse development environment. Info can be found at http://eclipse-cs.sourceforge.net/ project site. This site explains how to install the plug-in.

Now you need to tell the plugin to check according to our style conventions. Below are some instructions for the Helios version of Eclipse. The Juno version has some of these steps in the Project > Checkstyle > Properties area described below and some steps are in the main Eclipse Properties window.

  1. Open the project properties (right-click on the project name in the project panel)
  2. Select Checkstyle in the Properties dialog window
  3. Check the box to make checking active.
  4. Click the button for LocalCheckConfigurations
  5. Click New
  6. Choose Remote as the type, something like "csATappstate checks" for the name and description, and paste this in for the location:
    http://student2.cs.appstate.edu/classes/JavaCodingStyle/cs_appstate_checks.xml
    
  7. Check the box for Caching the configuration file
  8. Click OK. Click OK again.
  9. Re-enter Project Properties, Checkstyle properties, and now select the csATappstate checks instead of the Sun checks.
  10. Click OK and rebuild the project.

Once installed, you need to enable checking project-by-project. Highlight your project name and right-click (Macs: Ctrl-click) the project name. Select Properties from this menu. Select Checkstyle in the left-side panel of the Properties window. Check the box to enable checking. (Notice you can change the check configuration file here too.)

[BACK TO TOP]  
 
 

2.3 Command-line (student2.cs.appstate.edu)

There is a Unix command-line tool available. It is located in /usr/local/bin/checkstyle, but you should be able to simply say: checkstyle to run it.

Here are a couple of examples of usage:

% checkstyle Blah.java

% checkstyle *.java

% checkstyle *.java > checker.log

The last usage example redirects the checker output to the file checker.log which you can then print, email, view in an editor, etc.

[BACK TO TOP]  
 
 

2.4 Web-based checker

There is an online web-based checker located at:
http://euler.acadiau.ca/~giles/checkstyle/

Note that this checker does NOT check according to OUR style conventions. We hope to have a web-based version soon. Check back....

[BACK TO TOP]  
 
 

3.1 Java Source File

Files longer than 1000 lines are cumbersome and should be avoided.

Each Java source file contains a single public class or interface. When private classes and interfaces are associated with a public class, you can put them in the same source file as the public class. The public class should be the first class or interface in the file.

Java source files have the following ordering:

[BACK TO TOP]  
 
 

3.2 README Information File

This is often the starting point when exploring directories of source code. As such, it often describes the overall project, design decisions, limitations, exceptional features, etc.

This file should describe how to build the project and how to run the project.

[BACK TO TOP]  
 
 

4 - Indentation

Four spaces should be used as the unit of indentation. Tabs should be converted to spaces.

[BACK TO TOP]  

4.1 Line Length

Avoid lines longer than 80 characters, since they're not handled well by many terminals and tools.
NOTE: See section 10 for ways to break long lines.

[BACK TO TOP]  

4.2 Wrapping Lines

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

Here are some examples of breaking method calls:

someMethod(longExpression1, longExpression2, longExpression3, 
        longExpression4, longExpression5);
 
var = someMethod1(longExpression1,
                someMethod2(longExpression2,
                        longExpression3)); 

Following are two examples of breaking an arithmetic expression. The first is preferred, since the break occurs outside the parenthesized expression, which is at a higher level.

longName1 = longName2 * (longName3 + longName4 - longName5) + 4 * longname6; // PREFER longName1 = longName2 * (longName3 + longName4 - longName5) + 4 * longname6; // AVOID

Following are two examples of indenting method declarations. The first is the conventional case. The second would shift the second and third lines to the far right if it used conventional indentation, so instead it indents only 8 spaces.

//CONVENTIONAL INDENTATION someMethod(int anArg, Object anotherArg, String yetAnotherArg, Object andStillAnother) { ... } //INDENT 8 SPACES TO AVOID VERY DEEP INDENTS private static synchronized horkingLongMethodName(int anArg, Object anotherArg, String yetAnotherArg, Object andStillAnother) { ... }

Line wrapping for if statements should generally use the 8-space rule, since conventional (4 space) indentation makes seeing the body difficult. For example:

//DON'T USE THIS INDENTATION if ((condition1 && condition2) || (condition3 && condition4) ||!(condition5 && condition6)) { //BAD WRAPS doSomethingAboutIt(); //MAKE THIS LINE EASY TO MISS } //USE THIS INDENTATION INSTEAD if ((condition1 && condition2) || (condition3 && condition4) ||!(condition5 && condition6)) { doSomethingAboutIt(); } //OR USE THIS if ((condition1 && condition2) || (condition3 && condition4) ||!(condition5 && condition6)) { doSomethingAboutIt(); }
[BACK TO TOP]  
 
 

5 - Comments

Java programs can have two kinds of comments: implementation comments and documentation comments. Implementation comments are those found in C++, which are delimited by /*...*/, and //. Documentation comments (known as "doc comments") are Java-only, and are delimited by /**...*/. Doc comments can be extracted to HTML files using the javadoc tool.

Implementation comments are meant for commenting out code or for comments about the particular implementation. Doc comments are meant to describe the specification of the code, from an implementation-free perspective, to be read by developers who might not necessarily have the source code at hand.

Comments should be used to give overviews of code and provide additional information that is not readily available in the code itself. Comments should contain only information that is relevant to reading and understanding the program. For example, information about how the corresponding package is built or in what directory it resides should not be included as a comment.

Discussion of nontrivial or nonobvious design decisions is appropriate, but avoid duplicating information that is present in (and clear from) the code. It is too easy for redundant comments to get out of date. In general, avoid any comments that are likely to get out of date as the code evolves.

Note:The frequency of comments sometimes reflects poor quality of code. When you feel compelled to add a comment, consider rewriting the code to make it clearer.

Comments should not be enclosed in large boxes drawn with asterisks or other characters.
Comments should never include special characters such as form-feed and backspace.

[BACK TO TOP]  
 
 

5.1 Documentation Comments

Documentation comments are specified using the Javadoc notation.

The first line of a doc comment is "/**", and subsequent lines vertically align the asterisk, and */ ends the comment.

Documentation comments describe entities (files, classes, methods) at a specification level not a programming level.

Documentation comments immediately precede the entity they describe.

For further details, see the following resources:

[BACK TO TOP]  
 
 

5.1.1 File level

Optionally, a Java source file may start with a comment. Typical use of such a comment would identify the filename, any copyright information, version and author history, list of classes/interfaces defined within the file, etc.

Since many Java files only define a single class, this file level comment and the class level comment (see below) incorporate the same information. Thus, typically, the file level comment is not required.

/**
 * Filename.java
 *
 * Optional description of purpose of file/class; for example, to indicate
 * course and assignment.
 *
 * @author Harry Hacker
 * @version 12/25/2011
 *
 * COPYRIGHT (C) 1997 Harry Hacker. All Rights Reserved.
 */
[BACK TO TOP]  
 
 

5.1.2 Class Level

/**
 * Simple one-line description of class, ending with a period.
 *
 * Optional, longer description of purpose of class goes here.  This
 * comment can provide additional details of class design decisions, for
 * example. Many HTML tags are allowed!
 * NOTE: @author and @version tags are REQUIRED.
 *
 * @author Harry Hacker
 * @version 12/25/2011
 */
[BACK TO TOP]  
 
 

5.1.3 Method Level

Method doc comments should have the one line summary. The longer description is optional. Html formatting can be used to increase readability.

Method doc comments should include separate @param tags for each parameter that have the form: @param name description

Method doc comments should include an @return tag.

/**
 * Computes distance in Cartesian plane from this point to the given Point.
 *
 * Computation uses a variant of the familiar
 * Pythagorean Theorem.
 *
 * @param p the second Point of the line segment
 * @return non-negative distance between the two points
 *         or a negative value if the parameter is the same object as this
 */
public float getDistance(Point p)
{
 ...
}
[BACK TO TOP]  
 
 

5.2 Implementation Comment Formats

Programs can have various styles of implementation comments: block, single-line, and trailing.

Note:The frequency of comments sometimes reflects poor quality of code. When you feel compelled to add a comment, consider rewriting the code to make it clearer.

[BACK TO TOP]  
 
 

5.2.1 Block Comments

Block comments are used to provide longer descriptions within methods.

Block comments should be indented to the same level as the code they describe.

A block comment should be preceded by a blank line to set it apart from the rest of the code.

[BACK TO TOP]  
 
 

5.2.2 Single-Line Comments

Short comments can appear on a single line indented to the level of the code that follows.

Single-line comments can be of either form:

    /* A C-style single-line comment. */
    // Another style single-line comment.
[BACK TO TOP]  
 
 

5.2.3 Trailing Comments

Generally, trailing comments should be avoided as they too often get lost in the code. However, if used, they should be shifted far enough to separate them from the statements. If more than one short comment appears in a chunk of code, they should all be indented to the same tab setting.

Note:Notice how changing the code causes the alignment to require change too, leading to poor comment style.
Note:See earlier note about over-commenting.

Here's an example of a trailing comment:

if (a == 2) {
    return TRUE;            /* special case */
} else {
    return isPrime(a);      // works only for odd a
}
[BACK TO TOP]  
 
 

6.1 Number Per Line

Only one declaration per line.

/* This is correct: */
int level = 0;
int size = 0;

// This is not:
int level = 0, size = 0;

Use one space between the type and the identifier, as shown above.
Some programmers like to align declarations, but keeping this formatting becomes a code maintenance problem. (Consider what happens if level variable's type changes to Integer: many other entries must be moved - ugh.)

// This is bad style:
int	level;	        // indentation level
int	size;	         // size of table
Object	currentEntry;	 // currently selected table entry
[BACK TO TOP]  
 
 

6.2 Initialization

Initialize local variables when they are declared.

Note:This can lead to a slight execution inefficiency, but the gains of clarity and portability generally outweigh this consideration.

[BACK TO TOP]  
 
 

6.3 Placement

Put declarations only at the beginning of blocks. (A block is any code surrounded by curly braces "{" and "}".) Don't wait to declare variables until their first use; it can confuse the unwary programmer and hamper code portability within the scope.

void myMethod() {
    int int1 = 0;         // beginning of method block

    if (condition) {
        int int2 = 0;     // beginning of "if" block
        ...
    }
}

Note:This can lead to a slight execution inefficiency, but the gains of clarity and portability generally outweigh this consideration.

The one exception to the placement rule is indexes of for loops, which in Java can be declared in the for statement:

for (int i = 0; i < maxLoops; i++) { ... }

Avoid local declarations that "hide" declarations at higher levels. For example, do not declare the same variable name in an inner block:

int count;
...
myMethod() {
    if (condition) {
        int count = 0;     // AVOID!
        ...
    }
    ...
}
[BACK TO TOP]  
 
 

6.4 Class and Method Declarations

When coding Java classes and interfaces, the following formatting rules should be followed:

[BACK TO TOP]  
 
 

7.1 Simple Statements

Each line should contain at most one statement. Example:

argv++;       // Correct
argc--;       // Correct  
argv++; argc--;       // AVOID!
[BACK TO TOP]  
 
 

7.2 Compound Statements

A compound statement (also called a "block") is itself a single statement that contains a sequence of statements enclosed in braces "{ statements }".

The enclosed statements should be indented one more level than the compound statement (i.e., the braces).

The opening and closing braces should be on their own lines and be indented to the beginning of the compound statement.

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.

Blocks should not be left empty.
NOTE:If wanting to "stub out" a method use a valid return statement. Exception "catch" blocks should - at a minimum - call the printStackTrace() method on the exception object.

[BACK TO TOP]  
 
 

7.3 return Statements

A return statement with a value should not use parentheses unless they make the return value more obvious in some way. Example:

return;

return myDisk.size();

return (size ? size : defaultSize);

[BACK TO TOP]  
 
 

7.4 if, if-else, if else-if else Statements

The if-else class of statements should have the following form:

if (condition) 
{
    statements;
}
if (condition) 
{
    statements;
} 
else if (condition) 
{
    statements;
} 
else
{
    statements;
}
A series of if's nested inside of else's should take the more vertical form shown above.
if (condition) 
{
    statements;
} 
else 
{
    statements;
}

Note: if statements always use braces {}.

[BACK TO TOP]  
 
 

7.5 for Statements

A for statement should have the following form:

for (initialization; condition; update) 
{
    statements;
}
[BACK TO TOP]  
 
 

7.6 while Statements

A while statement should have the following form:

while (condition) 
{
    statements;
}
[BACK TO TOP]  
 
 

7.7 do-while Statements

A do-while statement should have the following form:

do 
{
    statements;
} while (condition);
[BACK TO TOP]  
 
 

7.8 switch Statements

A switch statement should have the following form:

switch (condition) 
{
    case ABC:
        statements;
        /* falls through */

    case DEF:
        statements;
        break;

    case XYZ:
        statements;
        break;

    default:
        statements;
        break;
}

Every time a case falls through (doesn't include a break statement), add a comment where the break statement would normally be. This is shown in the preceding code example with the /* falls through */ comment.

Every switch statement should include a default case. The break in the default case is redundant, but it prevents a fall-through error if later another case is added.

[BACK TO TOP]  
 
 

7.9 try-catch Statements

A try-catch statement should have the following format:

try 
{
    statements;
} 
catch (ExceptionClass e) 
{
    statements;
}

A try-catch statement may also be followed by finally, which executes regardless of whether or not the try block has completed successfully.

try 
{
    statements;
} 
catch (ExceptionClass e) 
{
    statements;
} 
finally 
{
    statements;
}

[BACK TO TOP]  
 
 

8.1 Blank Lines

Blank lines improve readability by setting off sections of code that are logically related.

One blank line should always be used in the following circumstances:

[BACK TO TOP]  
 
 

8.2 Blank Spaces

Blank spaces should be used in the following circumstances:

    a += c + d;
    a = (a + b) / (c * d);
    
    while (d++ = s++) {
        n++;
    }
    printSize("size is " + foo + "\n");

    for (expr1; expr2; expr3)

    myMethod((byte) aNum, (Object) x);
    myMethod((int) (cp + 5), ((int) (i + 3)) 
                                  + 1);
Blank spaces should NOT be used in the following circumstances: [BACK TO TOP]  
 
 

9 - Naming Conventions

Naming conventions make programs more understandable by making them easier to read. They can also give information about the function of the identifier; for example, whether it's a constant, package, or class, which can be helpful in understanding the code.


Identifier Type


Rules for Naming


Examples


Packages


The prefix of a unique package name is always written in all-lowercase ASCII letters and should be one of the top-level domain names, currently com, edu, gov, mil, net, org, or one of the English two-letter codes identifying countries as specified in ISO Standard 3166, 1981.

Subsequent components of the package name vary according to an organization's own internal naming conventions. Such conventions might specify that certain directory name components be division, department, project, machine, or login names.

com.sun.eng

com.apple.quicktime.v2

edu.cmu.cs.bovik.cheese

edu.appstate.fenwickjb.cs1440.lemonade


Classes


Class names should be nouns, in mixed case with the first letter capitalized and the first letter of each internal word capitalized (CamelCase). Try to keep your class names simple and descriptive. Use whole words; avoid acronyms and abbreviations (unless the abbreviation is much more widely used than the long form, such as URL or HTML).


class Raster;
class ImageSprite;


Interfaces


Interface names should be capitalized like class names.


interface RasterDelegate;
interface Storing;


Methods


Methods should be verbs, in mixed case with the first letter lowercase and the first letter of each internal word capitalized (camelCase).


run();
runFast();
getBackground();


Variables


Instance and class variables in mixed case with a lowercase first letter and internal "words" starting with capital letters (camelCase). Variable names should not start with underscore _ or dollar sign $ characters, even though both are allowed.

Variable names should be short yet meaningful. The choice of a variable name should be mnemonic; that is, designed to indicate to the casual observer the intent of its use. One-character variable names should be avoided except for temporary "throwaway" variables. Common names for temporary variables are i, j, k, m, and n for integers; c, d, and e for characters.


int i;
char c;
float myWidth;


Constants


The names of variables declared class constants and of ANSI constants should be all uppercase with words separated by underscores ("_"). (ANSI constants should be avoided, for ease of debugging.)


static final int MIN_WIDTH = 4;

static final int MAX_WIDTH = 999;

static final int GET_THE_CPU = 1;

[BACK TO TOP]  
 
 

10.1 Providing Access to Instance and Class Variables

Don't make any instance or class variable public without good reason.

[BACK TO TOP]  
 
 

10.2 Magic Number Constants

Numerical constants (literals) should not be coded directly, except for -1, 0, and 1, which can appear in a for loop as counter values.

Use named constants in place of these magic numbers.

int currMinSpeed = 40;  // magic number

private static final int DEFAULT_MAX_SPEED = 65; // named constant

int currMaxSpeed = DEFAULT_MAX_SPEED;
[BACK TO TOP]  
 
 

10.3 Parentheses

It is generally a good idea to use parentheses liberally in expressions involving mixed operators to avoid operator precedence problems. Even if the operator precedence seems clear to you, it might not be to others-you shouldn't assume that other programmers know precedence as well as you do.

if (a == b && c == d)     // AVOID!
if ((a == b) && (c == d)) // RIGHT
[BACK TO TOP]  
 
 

10.4 Returning Boolean Constants

Avoid redundant boolean constant return values

if (booleanExpression) {
    return true;
} else {
    return false;
}

should instead be written as

return booleanExpression;
[BACK TO TOP]  
 
 

10.5 Code Duplication

Code duplication is undesirable for several reasons, including code bloat and maintenance difficulties.

"Procedural abstraction" is the standard solution to code duplication. Abstract the duplicated code into its own method (a.k.a., procedure) and then invoke the procedure instead of duplicating.

Notice that procedure parameters can be used to vary the "duplicate" slightly.

[BACK TO TOP]  
 
 

10.6 Breaking long lines

It is acceptable to break statements onto multiple lines at operators. For example,

aLongishVariableName = anotherSignificantlyLongName + "this is okay"
                       + andSomeOtherStuff;

It is acceptable to break long function call statements at parameters. For example,

aLongishName = foo.aLongMethodName(parameterOne, parameterTwo, 
                                   parameterThree, parameterFour);
[BACK TO TOP]  
 
 
11.1 Good example
11.2 Bad example
11.3 Bad example checkstyle results

11.1 Good Example

Below is a sample Java class that demonstrates many of the coding style items described in this document. Here is the result of running javadoc on this file: Greeting.html.

/**
 * Greeting.java
 *
 * The following classes are defined in this file:
 * Greeting
 */

import java.util.Scanner;


/**
 * An obfuscated HelloWorld program to demonstrate coding style.
 *
 * A dual-purpose class to (1) play with the classic first program 
 * "Hello World", and (2) demonstrate proper coding styles.  Note that
 * to invoke a large number of style issues, the code is somewhat
 * (okay, largely :) obfuscation.
 *
 * @author Jay Fenwick
 * @version Dec 2011
 */
public class Greeting 
{
    private static final String DEFAULT_INTRO = "Hello";
    private String user;
    private Scanner keyboard;

    /**
     * Parameterless constructor, initializes keyboard input.
     */
    public Greeting()
    {
	keyboard = new Scanner(System.in);
    }

    /**
     * Alternate constructor.
     *
     * @param u user of the program
     */
    public Greeting(String u)
    {
	/* Notice this nifty way to initilize the keyboard Scanner WITHOUT
	   duplicating code by invoking the other constructor. */
	this();

	user = u;
    }

    /**
     * Builds a greeting.
     *
     * Uses Scanner object to get input from keyboard for customization.
     *
     * @param introduction customized greeting intro
     * @return a customized greeting
     */
    private String make(String introduction) 
    {
	String greeting = "Hello";

	if (introduction != null) 
	{
	    greeting = introduction;
	}

	// Customize with user's name!
	if (user == null)
	{
	    System.out.print("Please enter your name: ");
	    user = keyboard.nextLine();
	}
	greeting = greeting + ", " + user + ".";

	return greeting;
    }

    /**
     * Says default greeting.
     */
    public void say() 
    {
	/* Notice the nifty way to use overloaded method to avoid 
	   code duplication! */
	say(DEFAULT_INTRO);
    }

    /**
     * Says the greeting.
     *
     * Uses private internal method to customize.
     * 
     * @param intro customized greeting intro
     */
    public void say(String intro)
    {
	String greeting = make(intro);
	System.out.println(greeting);
    }

    /**
     * Driver to test it out.
     * 
     * @param args command-line arguments (not currently used)
     */
    public static void main(String[] args)
    {
	final int numTimes = 3;
	String[] hellos = {"Ola", "Aloha", "Bon Jour",};

	Greeting greeting = new Greeting("Unknown program user");
	greeting.say();
	
	greeting = new Greeting();
	for (int i = 0; i < numTimes; i++)
	{
	    greeting.say(hellos[i]);
	}
    }
}
[BACK TO TOP]  
 
 

11.2 Bad example

This is the good sample Java class from above, but with a couple of style errors. The next section below shows the results of checking the style of this file.

/**
 * Greeting.java
 *
 */

import java.util.Scanner;


/**
 * An obfuscated HelloWorld program to demonstrate coding style.
 *
 * A dual-purpose class to (1) play with the classic first program 
 * "Hello World", and (2) demonstrate proper coding styles.  Note that
 * to invoke a large number of style issues, the code is somewhat
 * (okay, largely :) obfuscation.
 *
 * @version Dec 2011
 */
public class Greeting 
{
    private static final String DEFAULT_INTRO = "Hello";
    private String user;
    private Scanner keyboard;

    /**
     * Parameterless constructor, initializes keyboard input.
     */
    public Greeting()
    {
	keyboard = new Scanner(System.in);
    }

    /**
     * Alternate constructor.
     *
     */
    public Greeting(String u)
    {
	/* Notice this nifty way to initilize the keyboard Scanner WITHOUT
	   duplicating code by invoking the other constructor. */
	this();

	user = u;
    }

    /**
     * Builds a greeting.
     *
     * Uses Scanner object to get input from keyboard for customization.
     *
     * @param introduction user's customized greeting intro (e.g., G'day)
     * @return a customized greeting
     */
    private String make(String introduction) 
    {
	String greeting = "Hello";

	if (introduction != null) 
	{
	    greeting = introduction;
	}

	// Customize with user's name!
	if (user == null)
	{
	    System.out.print("Please enter your name: ");
	    user = keyboard.nextLine();
	}
	greeting = greeting + ", " + user + ".";

	return greeting;
    }

    /**
     * Says default greeting.
     */
    public void say() 
    {
	/* Notice the nifty way to use overloaded method to avoid 
	   code duplication! */
	say(DEFAULT_INTRO);
    }

    /**
     * Says the greeting.
     *
     * Uses private internal method to customize.
     *
     * @param intro passing through user's greeting customization
     */
    public void say(String intro)
    {
	String greeting = make(intro);
	System.out.println(greeting);
    }

    /**
     * Driver to test it out.
     *
     * @param args command-line arguments are not used currently
     */
    public static void main(String[] args)
    {
	final int numTimes = 3;
	String[] hellos = {"Ola", "Aloha", "Bon Jour"};

	Greeting greeting = new Greeting("Unknown program user");
	greeting.say();
	
	greeting = new Greeting();
	for (int i=0; i < numTimes; i++)
	{
	    greeting.say(hellos[i]);
	}
    }
}
[BACK TO TOP]  
 
 

11.3 Bad example checkstyle results

Here is the output of the command-line checkstyle automated checker.

Greeting.java did not pass checkstyle
Starting audit...
Greeting.java:5: Line does not match expected header line of '^ \* @author .*$'.
Greeting.java:37:28: Expected @param tag for 'u'.
Greeting.java:104:19: Name 'numTimes' must match pattern '^[A-Z][A-Z0-9_]*$'.
Greeting.java:111:19: '=' is not preceded with whitespace.
Greeting.java:111:20: '=' is not followed by whitespace.
Audit done.

Each audit line indicates the file, line number, and an warning/error message. Optionally, a column value is given. The output above indicates 4 style violations:

  1. In the file: Greeting.java on line # 5, the class header documentation comment is required to include the @author javadoc tag. (Section 5.1.2)
  2. In the file: Greeting.java on line # 37 at column # 28, the method documenation comment is missing an @param javadoc tag. (Section 5.1.3)
  3. In the file: Greeting.java on line # 104 at column # 19, the choice of the variable name 'numTimes' must match pattern '^[A-Z][A-Z0-9_]*$' or it should have capital letters and underscores.
  4. In the file: Greeting.java on line # 111 at column # 19, the assignment operator in the for loop should have spaces before/after it. (Section 8.2)
  5. In the file: Greeting.java on line # 111 at column # 20, the assignment operator in the for loop should have spaces before/after it. (Section 8.2)
[BACK TO TOP]