Code Conventions for the JavaTM Programming Language

1 - Introduction

1.1 Why Have Code Conventions

Code conventions are important to programmers for a number of reasons: 

1.2 Acknowledgments


Copyright 1995-1999 Sun Microsysytems, Inc. All rights reserved

[2] Additional Specifications adapted directly from NASA GSFC Data Systems Technology JavaTM Style Guide.

 1.3 Distribution

This document is for Internal Use Only and may not be reproduced or distributed outside of the Space Telescope Science Institute.

2 - File Names

This section lists commonly used file suffixes and names.

2.1 File Suffixes

Java Software uses the following file suffixes:

File Type


Java source 
Java bytecode 

3 - Consistent Formatting

The guidelines in this section are written to improve the consistency of formatting of Java programming style within the Branch. This will ease the job of maintenance and will also make it easier for a programmer to transfer from one project to another.

3.1 White Space

Adding white space in the form of blank lines, spaces, and indentation significantly improves the readability of code.

3.1.1 Blank Lines

There should be at least one blank line between methods. Within a method careful use of blank lines between code "paragraphs" can greatly enhance readability by making the logical structure of a sequence of lines more obvious. Using blank lines to create paragraphs in code or comments can make programs more understandable. The following example illustrates how the use of blank lines helps break up lines of text into meaningful portions.
Example 3.1.1a - Code Paragraphing
public void joinGroupSucceeded(JoinGroupSuccessEvent iEvent) {
    Group lGroup = getPendingGroup(iEvent.getGroupName());
    if (lGroup != null) {
        // Remove lGroup from the pending list
        // Add the group to the joined group list
        joinedGroupTable.put(lGroup.getName(), lGroup);
    } // if
    // Notify listener of the event:
    Vector lListeners = null;
    synchronize(this) {
        lListeners = (Vector) joinGroupSuccessListeners.clone();
    } // synchronize
    for (int i = 0; i < lListeners.size(); ++i) {
        ((JoinGroupSuccessListener) lListeners.elementAt(i)).joinGroupSucceeded(iEvent);
    } // for
} // joinGroupSucceeded
However, overuse of blank lines can defeat the purpose of grouping and can actually reduce readability. Therefore, a single blank line should be used to separate sections of code within a method.

3.1.2 Spacing

Appropriate spacing enhances the readability of lexical elements.
    1. Do not put spaces around the primary operators: . and []:
obj.m a[i]
    1. Do not put a space before parentheses following method names.
exp(2, x)
    1. Do not put spaces between unary operators and their operands:
!p -b ++i -n
    1. Casts are the only exception. Do put a space between a cast and its operand:
(Clonable) object
    1. Always put spaces around assignment operators:
c1 = c2
    1. Commas should have one space (or a new line) after them:, 255)
    1. Semicolons should have one space (or a new line) after them:
for(i = 0; i < n; ++i)
    1. For other operators, generally put one space on either side of the operator:
x + y a < b && b < c

4 - Indentation

Four spaces should be used as the unit of indentation. The exact construction of the indentation (spaces vs. tabs) is unspecified. 

4.1 Line Length

Avoid lines longer than 80 characters, since they're not handled well by many terminals and tools.
Note: Examples for use in documentation should have a shorter line length -- generally no more than 70 characters. 

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);
lVar = someMethod1(longExpression1,
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.
someMethod(int iAnArg, Object iAnotherArg, String iYetAnotherArg,
           Object iAndStillAnother) {
private static synchronized horkingLongMethodName(int iAnArg,
        Object iAnotherArg, String iYetAnotherArg,
        Object iAndStillAnother) {
Line wrapping for if statements should generally use the 8-space rule, since conventional (4 space) indentation makes seeing the body difficult. For example:
if ((condition1 && condition2)
 || (condition3 && condition4)
    ||!(condition5 && condition6)) { //BAD WRAPS
    doSomethingAboutIt(); //MAKE THIS LINE EASY TO MISS
if ((condition1 && condition2) {
        || (condition3 && condition4)
        ||!(condition5 && condition6))
if ((condition1 && condition2) || (condition3 && condition4)
        ||!(condition5 && condition6)) {

5 - File Organization

A file consists of sections that should be separated by blank lines and Section Separators.

For an example of a Java program properly formatted, see "Java Source File Example"

5.1 Java Source Files

Each Java source file contains a single public class or interface. When private classes and interfaces are associated with a public class, they can be put 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: 

5.1.1 Beginning Comments - File Prolog

All source files should begin with a file prolog. The format should also be used for other files related to the program, such as scripts and Makefiles, although the comment indicator ('//') must be changed as appropriate. The file prolog contains project information, notes, development history, and any warnings.
Example 5.1.1a - File Prolog

/*=== File Prolog ============================================================

* This code was developed by The Space Telescope Science Institute, APT 

* project.

*--- Notes -------------------------------------------------------------------

* Anything relevant about the items in this file, including document 

* references, assumptions, constraints, restrictions abnormal termination 

* conditions, etc.

*=== End File Prolog ==========================================================


5.1.2 Package and Import Statements

The first non-comment line of all Java source files is a package statement. After that, import statements can follow.  Most IDE's have a method of automatically formatting the import statements.  This is the preferrred method of grouping them.
The use of wild cards in package imports is acceptable, and should be set in the user's IDE to occur when more than classes are imported from the same package.
Note: The first component 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.

For Space Telescope, the package name should always include "edu.stsci" as the beginning of the package name declaration.

5.1.3 Class and Interface Declarations

Each class or interface shall be preceeded by a documentation comment of the following format. The @deprecated and @see lines are to be used only if applicable.


* Description of the class. Include usage instructions. Embed code fragments

* in <PRE></PRE> tags.


* <P>This code was developed by The Space Telescope Science Institute for the

* APT Project.


* @deprecated (add this if the class is superceded by a new class)

* @see name of a related class or interface, fully qualified

* @see relatedClassName#methodInClass

* @see URL (for document references)


5.1.4 Class Format

Classes should have components specified in the following order:
Each section must be separated by white space. If appropriate, the programmer may also include a comment line to divide sections. For example:
* Constructs a Something class.
public Something () {
} // Constructor - Something
* Registers a new value for the variable
* @param object The new value to set.
public void setValue (Object iObject)
} // setValue

6 - 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.

Comments should never include special characters such as form-feed and backspace. 

6.1 Implementation Comment Formats

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

6.1.1 Block Comments

Block comments are used to provide descriptions of files, methods, data structures and algorithms. Block comments may be used at the beginning of each file and before each method. They can also be used in other places, such as within methods. Block comments inside a function or method 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.
 * Here is a block comment.

6.1.2 Single-Line Comments

Short comments can appear on a single line indented to the level of the code that follows. If a comment can't be written in a single line, it should follow the block comment format (see section 6.1.1). A single-line comment should be preceded by a blank line. Here's an example of a single-line comment in Java code (also see "Documentation Comments"):
if (condition) {
    //Handle the condition.

6.1.3 End-Of-Line Comments

The // comment delimiter can comment out a complete line or only a partial line. Examples of all three styles follow:
if (foo > 1) {
    // Do a double-flip.
} // if
else {
    return false;          // Explain why here.
} // else
//if (bar > 1) {
//    // Do a triple-flip.
//    ...
//} // if
//else {
//    return false;
//} // else

6.2 Documentation Comments

Note: See "Java Source File Example" for examples of the comment formats described here.
For further details, see "How to Write Doc Comments for Javadoc" which includes information on the doc comment tags (@return, @param, @see):

For further details about doc comments and javadoc, see the javadoc home page at:

Doc comments describe Java classes, interfaces, constructors, methods, and fields. Each doc comment is set inside the comment delimiters /**...*/, with one comment per class, interface, or member. This comment should appear just before the declaration:

 * The Example class provides ...
public class Example { ...
Notice that top-level classes and interfaces are not indented, while their members are. The first line of doc comment (/**) for classes and interfaces is not indented; subsequent doc comment lines each have 1 space of indentation (to vertically align the asterisks). Members, including constructors, have 4 spaces for the first doc comment line and 5 spaces thereafter.

The following are general guidelines for writing Doc Comment summary information. Again, see the documents listed above for additional information.

If you need to give information about a class, interface, variable, or method that isn't appropriate for documentation, use an implementation block comment (see section 6.1.1) or single-line (see section 6.1.2) comment immediately after the declaration. For example, details about the implementation of a class should go in such an implementation block comment following the class statement, not in the class doc comment.
Doc comments should not be positioned inside a method or constructor definition block, because Java associates documentation comments with the first declaration after the comment.

7 - Declarations

7.1 Number Per Line

One declaration per line is recommended since it encourages commenting. In other words,
int level; // indentation level
int size;  // size of table
is preferred over

int level, size;
Do not put different types on the same line. Example:
int foo,  fooarray[]; //WRONG!
Note: The examples above use one space between the type and the identifier. Another acceptable alternative is to use tabs, e.g.:
int     level;           // indentation level
int     size;            // size of table
Object  currentEntry;   // currently selected table entry

7.2 Initialization

Try to initialize local variables where they're declared. The only reason not to initialize a variable where it's declared is if the initial value depends on some computation occurring first.

7.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
    } // if
} // myMethod
The one exception to the 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!
    } // if
} // myMethod

7.4 Class and Interface Declarations

When coding Java classes and interfaces, the following formatting rules should be followed: 
·No space between a method name and the parenthesis "(" starting its parameter list 

·Closing brace "}" starts a line by itself indented to match its corresponding opening statement, except when it is a null statement the "}" should appear immediately after the "{"

·Closing braces "}" should contain a comment indicating what they are closing (except in the case of empty methods). 

public class Sample extends Object {
    int fVar1;
    int fVar2;
    Sample(int i, int j) {
        fVar1 = i;
        fVar2 = j;
    } // Sample
    int emptyMethod() {}
} // Class Sample
·Methods are separated by a blank line 
·Changes to methods should include a Block Comment detailing the change in the method.Note that this method change history is not documentation that is displayed to the end user. For example:
    * This method is a sample method which does nothing except demonstrate
    * valid documentation styles.
    * Private Change History:
    * Changed logic to set global parameter xyz in support of OPR 12345.
    public void sampleMethod() {
    } // sampleMethod

8 - Statements

8.1 Simple Statements

Each line should contain at most one statement. Example:
argv++;       // Correct
argc--;       // Correct  
argv++; argc--;       // AVOID!

8.2 Compound Statements

Compound statements are statements that contain lists of statements enclosed in braces "{ statements }". See the following sections for examples.

8.3 return Statements

Areturn statement with a value should not use parentheses unless they make the return value more obvious in some way. Example:
return myDisk.size();
return (size == defaultSize);

8.4 if, if-else, if else-if else Statements

Theif-else class of statements should have the following form:
if (condition) {
if (condition) {
} else {
if (condition) {
} else if (condition) {
} else {
Note:if statements always use braces {}. Avoid the following error-prone form:
if (condition) //AVOID! THIS OMITS THE BRACES {}!

8.5 for Statements

Afor statement should have the following form:
for (initialization; condition; update) {
An empty for statement (one in which all the work is done in the initialization, condition, and update clauses) should have the following form:
for (initialization; condition; update);
When using the comma operator in the initialization or update clause of a for statement, avoid the complexity of using more than three variables. If needed, use separate statements before the for loop (for the initialization clause) or at the end of the loop (for the update clause).

8.6 while Statements

Awhile statement should have the following form:
while (condition) {
An empty while statement should have the following form:
while (condition);

8.7 do-while Statements

Ado-while statement should have the following form:
do {
} while (condition);

8.8 switch Statements

Aswitch statement should have the following form:
switch (condition) {
    case ABC:
        /* falls through */
    case DEF:
    case XYZ:
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.
Everyswitch 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.

8.9 try-catch Statements

Atry-catch statement should have the following format:
try {
} catch (ExceptionClass e) {
Atry-catch statement may also be followed by finally, which executes regardless of whether or not the try block has completed successfully.
try {
} catch (ExceptionClass e) {
} finally {

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


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. 



Class names should be nouns, in mixed case with the first letter of each internal word capitalized. 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; 

Interface names should be capitalized like class names. 
interface RasterDelegate;

interface Storing; 

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


Member Variables 
Member variables should start with an `f' and then capitalize the first letter of each word.
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 ijkm, and n for integers; c,d, and e for characters. These do not require use of the intial `f'.
int             fLength;
int             i;
char            c;
float           fMyWidth;
Object          fParent;
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; 

Method Parameters
These are variables passed into methods as parameters.They must start with an `i' and conform to the Member Variables naming conventions.
int iMyVariable
Object iMyObject
Local Variables
All locally scoped variables must start with an `l' and conform to the Member Variables naming conventions.
int lNumberOfLoops
Object lTemporaryObject

final Object lFINAL_OBJECT

Non-Final Static Variables
Non-Final Static Variables must start with an `s' and conform to the Member Variable naming conventions.
static int sNumberOfLoops

10 - Programming Practices

10.1 Providing Access to Instance and Class Variables

Don't make any instance or class variable public without good reason. Often, instance variables don't need to be explicitly set or gotten-often that happens as a side effect of method calls.
One example of appropriate public instance variables is the case where the class is essentially a data structure, with no behavior. In other words, if you would have used a struct instead of a class (if Java supported struct), then it's appropriate to make the class's instance variables public.

Instance or class variables generally should always be accessed from accessor methods, even from within the class.Making them public or circumventing the accessor methods within the class are strongly discouraged without careful consideration of the risks and benefits.

If performance is an issue, consider finalizing the accessor methods, although, keep in mind that they cannot be overridden in sub-classes. If finalizing the accessor methods is not acceptable, and performance concerns obviously outweigh the maintainability of the code, only then may instance and class variables be accessed directly from inside the class.

10.2 Referring to Class Variables and Methods

Avoid using an object to access a class (static) variable or method. Use a class name instead. For example:
classMethod();             //OK
AClass.classMethod();      //OK
anObject.classMethod();    //AVOID!

10.3 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.

10.4 Variable Assignments

Avoid assigning several variables to the same value in a single statement. It is hard to read. Example:
fooBar.fChar = barFoo.lchar = 'c'; // AVOID!
Do not use the assignment operator in a place where it can be easily confused with the equality operator. Example:

if (c++ = d++) {        // AVOID! (Java disallows)
should be written as
if ((c++ = d++) != 0) {
Do not use embedded assignments in an attempt to improve run-time performance. This is the job of the compiler. Example:
d = (a = b + c) + r;        // AVOID!
should be written as
a = b + c;
d = a + r;

10.5 Miscellaneous Practices

10.5.1 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

10.5.2 Returning Values

Try to make the structure of your program match the intent. Example:
if (booleanExpression)
    return true;
} else {
    return false;
should instead be written as
return booleanExpression;

10.5.3 Special Comments

Use TODO in a comment to flag something that still needs to be done.  Where appropriate, add the PR number or developer initials as well to make TODOs easier to hone in on.

11 - IDE Autoformat Settings

Most modern IDEs are capable of automatically formatting java files.  This is a useful feature, but can cause unneccessary conflicts in CVS if two developers use different formatting settings.  For this reason, we have adopted the following automatic formatting settings, that should be settable from any IDE used.

11.1. Use UNIX line separators ("\n").

11.2. Trailing whitespaces should be removed automatically.

11.3. Wildcards in import statements

Number of imports before using .* is 5.

11.4. Indentation and Tabs

Indentation should be 4 spaces per level.  Tabs should not be used, but should be replaced by spaces.

11.5. Braces

Opening braces are on the same line as the parent statement. Closing braces start a new line and are aligned with the indentation of the parent statement. Child statements should be on the same line as any closing braces for their parent.  e.g.:

// while
while (condition) {

// if..else
if (condition) {
} else {

// try..catch
try {
} catch (Exception ex) {
} finally {

// try..catch
switch (i) {
    case 1:

12 - Code Examples

12.1 Java Source File Example

The following example shows how to format a Java source file containing a single public class. Interfaces are formatted similarly.

/*=== File Prolog ===============================================================
* This code was developed by The Space Telescope Science Institute, APT project.
*--- Notes ----------------------------------------------------------------------
* This is a test class that is not used functionally. It is being written to
* provide an example of the Java Style guidelines presented in this document.
*=== End File Prolog ============================================================
package edu.stsci.apt.testpackage;
import java.awt.event.ActionEvent;
import edu.stsci.starview2.testpackage.FirstClass;
import edu.stsci.starview2.testpackage.FourthClass;
import edu.stsci.starview2.testpackage.SecondClass;
import edu.stsci.starview2.testpackage.ThirdClass;
 * Implements a test class for use in describing Java coding style
 * guidelines.
 * <P>This code was developed by the Space Telescope Science Institute
 * APT Team.
public class TestClass {
     * Identifies an acceptable string returned from the getValidity
     * method.
    public static final String RETURN_IS_VALID = "some value";
    private int fNumberOfThings;
     * Constructs a new TestClass Object.
    public TestClass() {
        // TODO - No logic included for sample program
     * Determines whether or not this class is valid.
     * @return A String identifying the validity of this class.
     * @see #RETURN_IS_VALID
    public String getValidity() {
        No logic included for sample program.
        If you can think of some you may add it.
     * Returns the number of things registered with this class
     * @return The number of things registered with this class.
    public int getNumberOfThings() {
        return fNumberOfThings;
     * Registers a new value for the number of things of this
     * class.
     * @param numberOfThings The new number of things to register
     * with this class.
    public void setNumberOfThings(int iNumberOfThings) {
         fNumberOfThings = iNumberOfThings;

Appendix A - Developer Concerns

This section is simply a list of items that a software developer should consider when developing Java code.

A.1 Classes

·Large class files slow down the JVM.  If a class begins to grow too large, consider splitting it into several smaller classes.
·Consider whether a class should implement the Cloneable and/or Serializable interfaces.

·If a class implements Cloneable, ensure that its implementation of clone() performs a deep copy.

·Consider defining a default (no-argument) constructor so that instances can be created via Class.newInstance() and Beans.instantiate().

·Use interfaces to separate functionality from implementation.

oCode written in terms of the abstract (interface) type does not need to change when the implementation class changes.

oDifferent implementations of the interface can be used, even at the same time.

oOther (unforeseen) classes can implement the interface if it becomes necessary, while they are only allowed to inherit from a single class.

oThe interface provides a distinct location where the behavior is defined.

·A class that overrides Object.equals() should also override Object.hashCode(), and vice-versa.This allows objects of the class to be properly inserted into container objects.

A.2 Threads

·Do not depend upon a particular implementation of threads since the virtual machine specification does not specify how threads will be scheduled.
·In order to promote reuse, always assume that a method may be called by multiple threads.Synchronization should be used on all methods that change or read the internal state of the object.

A.3 Portability

·Consider detailed optimizations only on computers where they prove necessary. Optimized code is often obscure. Optimizations for one computer may produce worse code on another.Document code that is obscure due to performance optimizations and isolate the optimizations as much as possible.
·Native methods are inherently non-portable. Organize source files so that the computer-independent code and the computer-dependent code are in separate classes.If the program is moved to a new computer, it will be clear which classes need to be changed for the new platform.

A.4 Performance

·When performance is important, as in real-time systems, use techniques to enhance performance.If the code becomes 'tricky' (i.e. possibly unclear), add comments to aid the reader.
·Enable compiler optimizations when compiling performance-critical classes. This will enable in-lining of static, final, and private methods.

Last update 09/14/2007 by Rob Douglas