Java Coding Style by Achut Reddy
Java Coding Style by Achut Reddy
Achut Reddy
Server Management Tools Group
Sun Microsystems, Inc.
Created: January 27, 1998
Last modified: May 30, 2000
ABSTRACT
The importance and benefits of a consistent coding style are well known. This document describes a set of coding
standards and recommendations for programs written in the Java language. It is intended for all Java software de-
velopers. It contains no material proprietary to Sun, and may be freely distributed outside Sun as well.
Feedback in the form of corrections or suggestions for improvement are welcomed. Comments may be sent to
achut@eng.sun.com.
Table of Contents
1.0 Introduction.......................................................................................................................1
1.1 Background ...................................................................................................................1
1.2 Acknowledgments.........................................................................................................1
8.0 Statements..........................................................................................................................16
8.1 Simple statements .........................................................................................................16
8.1.1 Assignment and expression statements................................................................16
8.1.2 Local variable declarations ..................................................................................16
8.1.3 Array declarations................................................................................................16
8.1.4 return statement .................................................................................................17
8.2 Compound statements...................................................................................................17
8.2.1 Braces style ..........................................................................................................17
8.2.2 Allowed exception to braces rule.........................................................................17
8.2.3 if statement ........................................................................................................18
8.2.4 for statement ......................................................................................................18
8.2.5 while statement ...................................................................................................18
8.2.6 do-while statement .............................................................................................18
8.2.7 switch statement ................................................................................................18
8.2.8 try statement .......................................................................................................19
8.2.9 synchronized statement ....................................................................................19
8.3 Labeled statements........................................................................................................19
References................................................................................................................................20
1. A tip for vi users: this can be accomplished easily by positioning the cursor on column 1 of the first import statement
and typing: !}sort<RETURN>
Names of fields being used as constants should be all upper-case, with underscores separating words. The
following are considered to be constants:
1. All static final primitive types (Remember that all interface fields are inherently static
final).
2. All static final object reference types that are never followed by "." (dot).
3. All static final arrays that are never followed by "[" (dot).
Examples:
MIN_VALUE, MAX_BUFFER_SIZE, OPTIONS_FILE_NAME
One-character field names should be avoided except for temporary and looping variables. In these cases,
use:
• b for a byte
1. In Java, constructors are not considered methods; constructors of course always have the same name as the class.
1. Some judgement is called for in the case of complex expressions, which may be clearer if the “inner” operators are not
surrounded by spaces and the “outer” ones are.
4.3 Indentation
Line indentation is always 4 spaces1, for all indentation levels.
The construction of the indentation may include tabs as well as spaces in order to reduce the file size; how-
ever, you may not change the hard tab settings to accomplish this. Hard tabs must be set every 8 spaces
Note: If this rule was not followed, tabs could not be used because they would lack a well-
defined meaning.
4.4 Continuation lines
Lines should be limited to 80 columns (but not necessarily 80 bytes, for non-ASCII encodings). Lines long-
er than 80 columns should be broken into one or more continuation lines, as needed. All the continuation
lines should be aligned, and indented from the first line of the statement. The amount of the indentation
depends on the type of statement.
If the statement must be broken in the middle of a parenthesized expression, such as for compound state-
ments, or for the parameter list in a method invocation or declaration, the next line should be aligned with
the first character to the right of the first unmatched left parenthesis in the previous line. In all other cases,
the continuation lines should be indented by a full standard indentation (4 spaces). If the next statement
after a continuation line is indented by the same amount as the continuation line, then a single blank line
should immediately follow the opening brace to avoid confusing it with the continuation line. It is accept-
able to break a long line sooner than absolutely necessary, especially if it improves readability.
Examples:
// RIGHT
foo(long_expression1, long_expression2, long_expression3,
long_expression4);
// RIGHT
foo(long_expression1,
long_expression2,
long_expression3,
long_expression4);
1. This is a difference from the predominant indentation style of 8 spaces used in C programs; it is an acknowledgment
that typical Java programs tend to have more levels of nesting than typical C programs.
statements;
}
A continuation line should never start with a binary operator. Never break a line where normally no white
space appears, such as between a method name and its opening parenthesis, or between an array name and
its opening square bracket. Never break a line just before an opening brace “{”. Examples:
// WRONG
while (long_expression1 || long_expression2 || long_expression3)
{
}
// RIGHT
while (long_expression1 || long_expression2 ||
long_expression3) {
}
5.0 Comments
Java supports three kinds of comments: documentation, block, and single-line comments. These are de-
scribed separately in the subsequent sections below. Here are some general guidelines for comment usage:
• Comments should help a reader understand the purpose of the code. They should guide the reader
through the flow of the program, focusing especially on areas which might be confusing or obscure.
• Avoid comments that are obvious from the code, as in this famously bad comment example:
i = i + 1; // Add one to i
• Remember that misleading comments are worse than no comments at all.
• Avoid putting any information into comments that is likely to become out-of-date.
• Avoid enclosing comments in boxes drawn with asterisks or other fancy typography.
• Temporary comments that are expected to be changed or removed later should be marked with the spe-
cial tag “XXX:” so that they can easily be found afterwards. Ideally, all temporary comments should
have been removed by the time a program is ready to be shipped. Example:
// XXX: Change this to call sort() when the bugs in it are fixed
list->mySort();
For further extensive guidance in proper comment usage, see references [11] and [13].
5.1 Documentation comments
Java has support for special comments documenting types (classes and interfaces), fields (variables), con-
structors, and methods, hereafter referred to collectively as declared entities (see section 6.1.2 for guide-
lines on which declared entities should have documentation comments). The javadoc program can then
be used to automatically extract these comments and generate formatted HTML pages.
A documentation comment should immediately precede the declared entity, with no blank lines in between.
The first line of the comment should be simply the characters /** with no other text on the line, and should
be aligned with the following declared entity. Subsequent lines consist of an asterisk, followed by a single
space, followed by comment text, and aligned with the first asterisk of the first line. The first sentence of
the comment text is special, and should be a self-contained summary sentence. A sentence is defined as text
Avoid the assembly language style of commenting every line of executable code with a trailing comment.
6.0 Classes
A class declaration looks like the following. Elements in square brackets [] are optional.
[ClassModifiers] class ClassName [Inheritances] {
ClassBody
}
1. It is tempting to want to group these declarations together by access level; i.e., group all the public members together,
then all the default access member, then all the protected members, etc. However, static/non-static is a more important
conceptual distinction than access level. Also, there are so many different access levels in Java that it becomes too con-
fusing, and does not work well in practice.
2. The private protected access level is obsolete and should not be used.
7.0 Interfaces
Interfaces follows a similar style to classes. An interface declaration looks like the following. Elements in
square brackets “[]” are optional.
[public] interface InterfaceName [extends SuperInterfaces] {
InterfaceBody
}
SuperInterfaces is the name of an interface, or a comma-separated list of interfaces. If more than one in-
terface is given, then they should be sorted in lexical order.
8.0 Statements
8.1 Simple statements
8.1.1 Assignment and expression statements
Each line should contain at most one statement. For example,
a = b + c; count++; // WRONG
a = b + c; // RIGHT
count++; // RIGHT
8.1.2 Local variable declarations
Generally local variable declarations should be on separate lines; however, an exception is allowable for
temporary variables that do not require initializers. For example,
int i, j = 4, k; // WRONG
int i, k; // acceptable
int j = 4; // RIGHT
Local variables may be declared final in order to make the compiler enforce that the variable is not
changed after initialization, as well as to provide useful documentation to the reader. Local variables must
be declared final in order to make them available to local inner classes.
if (condition) {
statements;
} else {
statements;
}
if (condition) {
statements;
} else if (condition) {
statements;
} else {
statements;
}
8.2.4 for statement
for (initialization; condition; update) {
statements;
}
8.2.5 while statement
while (condition) {
statements;
}
For “infinite” loops, use the following rather than “for (;;) { ... }” :
while (true) {
statements;
}
8.2.6 do-while statement
do {
statements;
} while (condition);
8.2.7 switch statement
switch (condition) {
case 1:
case 2:
statements;
break;
case 3:
statements;
break;
default:
statements;
break;
}
try {
statements;
} finally {
statements;
}
try {
statements;
} catch (exception-declaration) {
statements;
} finally {
statements;
}
8.2.9 synchronized statement
synchronized (expression) {
statements;
}
8.3 Labeled statements
Labeled statements should always be enclosed in braces “{}”. The label itself should be indented to the
normal indentation level, followed by a colon, single space, and opening brace. The closing brace should
have a trailing comment on the same line with the label repeated:
statement-label: {
} // statement-label
[2] Plocher, J., Byrne, S., Vinoski, S., “C++ Programming Style With Rationale”, Sun Internal
[3] Gosling, J., Joy, B., Steele, G., “The Java Language Specification”, Addison-Wesley, 1996
[4] Skinner, G., Shah, S., Shannon, B., “C Style and Coding Standards”, Sun Internal Paper,
Token 2151, Sun Electronic Library, 1990.
[6] Pike, R., “Notes on Programming in C”, Bell Labs technical paper.
[7] Cannon, L., Spencer, H., Keppel, D., et al, “Recommend C Style and Coding Standards”,
updated version of “Indian Hill C Style and Coding Standards”, AT&T internal technical
paper.
[8] Goldsmith, D., Palevich, J., “Unofficial C++ Style Guide”, develop, April 1990.
[11] Baecker, R., Marcus, A., Human Factors and Typography for More Readable Programs,
ACM Press, 1990, especially Appendix C: An Essay on Comments.
[12] Kernighan, B., Ritchie, D., The C Programming Language, Prentice-Hall, 1978
[13] McConnell, Steven, Code Complete, Microsoft Press, 1993, Chapter 19: Self-Documenting
Code
[14] Flanagan, David, JAVA in a Nutshell, O’Reilly & Associates, 1997, Chapter 5 - Inner
Classes and Other New Language Features
package com.sun.examples;
import java.applet.Applet;
import java.awt.Point;
/**
* A class to demonstrate good coding style.
*/
public class CodingStyleExample extends Applet implements Runnable {
/**
* Compute the total distance between a set of Points.
* @param starshipCoordinates the locations of all known starships
* @param numberOfPoints the number of points in the array
* @return the total distance
*/
public int computeDistances(Point starshipCoordinates[],
int numberOfPoints) throws Exception {
int distance = 0; // accumulates distances
return distance;
}
/**
* Called whenever Thread.start() is called for this class
*/
public void run() {
try {
name.append("X");
System.out.println(name);
} catch (Exception e) {
name = new StringBuffer(BUFFER_SIZE);
}
}
}
Appendix B - Java Coding Style Quick Reference Sheet
Naming Conventions
Braces style “K&R” braces style: class declarations, method declarations, block statements, array initializers
Blank lines Before: a block or single-line comment, unless it is the first line in a block
Between: class or method declarations; last variable declaration and first method declaration.
After: copyright/ID comment, package declaration, import section
Order of method modifiers public protected private abstract static final synchronized native