Java Coding Conventions
Java Coding Conventions
1 Introduction
1.1 Why Have Code Conventions 1.2 Acknowledgments
2 File Names
2.1 File Suffixes 2.2 Common File Names
3 File Organization
3.1 Java Source Files 3.1.1 Beginning Comments 3.1.2 Package and Import Statements 3.1.3 Class and Interface Declarations
4 Indentation
4.1 Line Length 4.2 Wrapping Lines
5 Comments
5.1 Implementation Comment Formats 5.1.1 Block Comments 5.1.2 Single-Line Comments 5.1.3 Trailing Comments 5.1.4 End-Of-Line Comments 5.2 Documentation Comments
6 Declarations
6.1 Number Per Line 6.2 Initialization 6.3 Placement 6.4 Class and Interface 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
11 Code Examples
11.1 Java Source File Example
file:///E|/copy1/prashant/books/Books/Docs/Java%20Coding%20Conventions/CodeConvTOC.doc.html (2 of 3) [8/1/02 8:27:47 AM]
file:///E|/copy1/prashant/books/Books/Docs/Java%20Coding%20Conventions/CodeConventions.doc.html
TM
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.
1.2 Acknowledgments
This document reflects the Java language coding standards presented in the Java Language Specification, from Sun Microsystems, Inc. Major contributions are from Peter King, Patrick Naughton, Mike DeMoney, Jonni Kanerva, Kathy Walrath, and Scott Hommel. This document is maintained by Scott Hommel. Comments should be sent to [email protected]
file:///E|/copy1/prashant/books/Books/Docs/Java%20Coding%20Conventions/CodeConventions.doc1.html
2 - File Names
This section lists commonly used file suffixes and names.
Java source
.java
Java bytecode
.class
GNUmakefile
The preferred name for makefiles. We use gnumake to build our software.
file:///E|/copy1/prashant/books/Books/Docs/Java%20Coding%20Conventions/CodeConventions.doc1.html
README
The preferred name for the file that summarizes the contents of a particular directory.
file:///E|/copy1/prashant/books/Books/Docs/Java%20Coding%20Conventions/CodeConventions.doc2.html
3 - File Organization
A file consists of sections that should be separated by blank lines and an optional comment identifying each section. Files longer than 2000 lines are cumbersome and should be avoided. For an example of a Java program properly formatted, see "Java Source File Example" on page 19.
Beginning comments (see "Beginning Comments" on page 4) Package and Import statements Class and interface declarations (see "Class and Interface Declarations" on page 4)
3.1.1 Beginning Comments All source files should begin with a c-style comment that lists the class name, version information, date, and copyright notice: /* * Classname * * Version information * * Date * * Copyright notice */
file:///E|/copy1/prashant/books/Books/Docs/Java%20Coding%20Conventions/CodeConventions.doc2.html
3.1.2 Package and Import Statements The first non-comment line of most Java source files is a package statement. After that, import statements can follow. For example: package java.awt; import java.awt.peer.CanvasPeer; 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. 3.1.3 Class and Interface Declarations The following table describes the parts of a class or interface declaration, in the order that they should appear. See "Java Source File Example" on page 19 for an example that includes comments.
Notes
See "Documentation Comments" on page 9 for information on what should be in this comment.
This comment should contain any class-wide or interface-wide information that wasn't appropriate for the class/interface documentation comment.
file:///E|/copy1/prashant/books/Books/Docs/Java%20Coding%20Conventions/CodeConventions.doc2.html
First the public class variables, then the protected, then package level (no access modifier), and then the private.
5 Instance variables
First public, then protected, then package level (no access modifier), and then private.
6 Constructors
7 Methods
These methods should be grouped by functionality rather than by scope or accessibility. For example, a private class method can be in between two public instance methods. The goal is to make reading and understanding the code easier.
file:///E|/copy1/prashant/books/Books/Docs/Java%20Coding%20Conventions/CodeConventions.doc3.html
4 - Indentation
Four spaces should be used as the unit of indentation. The exact construction of the indentation (spaces vs. tabs) is unspecified. Tabs must be set exactly every 8 spaces (not 4).
Break after a comma. Break before an operator. Prefer higher-level breaks to lower-level breaks. Align the new line with the beginning of the expression at the same level on the previous line. If the above rules lead to confusing code or to code that's squished up against the right margin, just indent 8 spaces instead.
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
file:///E|/copy1/prashant/books/Books/Docs/Java%20Coding%20Conventions/CodeConventions.doc3.html (1 of 3) [8/1/02 8:28:39 AM]
file:///E|/copy1/prashant/books/Books/Docs/Java%20Coding%20Conventions/CodeConventions.doc3.html
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(); }
file:///E|/copy1/prashant/books/Books/Docs/Java%20Coding%20Conventions/CodeConventions.doc3.html (2 of 3) [8/1/02 8:28:39 AM]
file:///E|/copy1/prashant/books/Books/Docs/Java%20Coding%20Conventions/CodeConventions.doc3.html
Here are three acceptable ways to format ternary expressions: alpha = (aLongBooleanExpression) ? beta : gamma; alpha = (aLongBooleanExpression) ? beta : gamma; alpha = (aLongBooleanExpression) ? beta : gamma;
file:///E|/copy1/prashant/books/Books/Docs/Java%20Coding%20Conventions/CodeConventions.doc4.html
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 mean 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.
file:///E|/copy1/prashant/books/Books/Docs/Java%20Coding%20Conventions/CodeConventions.doc4.html
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. */ Block comments can start with /*-, which is recognized by indent(1) as the beginning of a block comment that should not be reformatted. Example: /** Here is a block comment with some very special * formatting that I want indent(1) to ignore. * * one * two * three */
Note: If you don't use indent(1), you don't have to use /*- in your code or make any other concessions to the possibility that someone else might run indent(1) on your code. See also "Documentation Comments" on page 9. 5.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 5.1.1). A singleline comment should be preceded by a blank line. Here's an example of a single-line comment in Java code (also see "Documentation Comments" on page 9): if (condition) { /* Handle the condition. */ ... } 5.1.3 Trailing Comments Very short comments can appear on the same line as the code they describe, but should be shifted far enough to separate them from the statements. If more than one short comment appears in a chunk of
file:///E|/copy1/prashant/books/Books/Docs/Java%20Coding%20Conventions/CodeConventions.doc4.html (2 of 4) [8/1/02 8:28:45 AM]
file:///E|/copy1/prashant/books/Books/Docs/Java%20Coding%20Conventions/CodeConventions.doc4.html
code, they should all be indented to the same tab setting. Here's an example of a trailing comment in Java code: if (a == 2) { return TRUE; } else { return isPrime(a); } 5.1.4 End-Of-Line Comments The // comment delimiter can comment out a complete line or only a partial line. It shouldn't be used on consecutive multiple lines for text comments; however, it can be used in consecutive multiple lines for commenting out sections of code. Examples of all three styles follow: if (foo > 1) { // Do a double-flip. ... } else { return false; // Explain why here. } //if (bar > 1) { // // // Do a triple-flip. // ... //} //else { // return false; //}
file:///E|/copy1/prashant/books/Books/Docs/Java%20Coding%20Conventions/CodeConventions.doc4.html
For further details about doc comments and javadoc, see the javadoc home page at: http://java.sun.com/products/jdk/javadoc/ 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. 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 5.1.1) or single-line (see section 5.1.2) comment immediately after the declaration. For example, details about the implementation of a class should go in 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.
file:///E|/copy1/prashant/books/Books/Docs/Java%20Coding%20Conventions/CodeConventions.doc5.html
6 - Declarations
6.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 int Object level; size; currentEntry; // indentation level // size of table // currently selected table entry
6.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.
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.
file:///E|/copy1/prashant/books/Books/Docs/Java%20Coding%20Conventions/CodeConventions.doc5.html
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!
No space between a method name and the parenthesis "(" starting its parameter list Open brace "{" appears at the end of the same line as the declaration statement 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 "{" class Sample extends Object { int ivar1; int ivar2; Sample(int i, int j) { ivar1 = i;
file:///E|/copy1/prashant/books/Books/Docs/Java%20Coding%20Conventions/CodeConventions.doc5.html
file:///E|/copy1/prashant/books/Books/Docs/Java%20Coding%20Conventions/CodeConventions.doc6.html
7 - Statements
7.1 Simple Statements
Each line should contain at most one statement. Example: argv++; // Correct argc--; // Correct argv++; argc--; // AVOID!
The enclosed statements should be indented one more level than the compound statement. The opening brace should be at the end of the line that begins the compound statement; the closing brace should begin a line 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.
file:///E|/copy1/prashant/books/Books/Docs/Java%20Coding%20Conventions/CodeConventions.doc6.html
The if-else class of statements should have the following form: if (condition) { statements; } if (condition) { statements; } else { statements; } if (condition) { statements; } else if (condition) { statements; } else{ statements; }
Note: if statements always use braces {}. Avoid the following error-prone form: if (condition) //AVOID! THIS OMITS THE BRACES {}! statement;
file:///E|/copy1/prashant/books/Books/Docs/Java%20Coding%20Conventions/CodeConventions.doc6.html
file:///E|/copy1/prashant/books/Books/Docs/Java%20Coding%20Conventions/CodeConventions.doc6.html
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.
file:///E|/copy1/prashant/books/Books/Docs/Java%20Coding%20Conventions/CodeConventions.doc7.html
8 - White Space
8.1 Blank Lines
Blank lines improve readability by setting off sections of code that are logically related. Two blank lines should always be used in the following circumstances:
G G
Between methods Between the local variables in a method and its first statement Before a block (see section 5.1.1) or single-line (see section 5.1.2) comment Between logical sections inside a method to improve readability
A keyword followed by a parenthesis should be separated by a space. Example: while (true) { ... }
Note that a blank space should not be used between a method name and its opening parenthesis. This helps to distinguish keywords from method calls.
G G
A blank space should appear after commas in argument lists. All binary operators except . should be separated from their operands by spaces. Blank spaces should never separate unary operators such as unary minus, increment ("++"), and decrement ("-") from their operands. Example:
file:///E|/copy1/prashant/books/Books/Docs/Java%20Coding%20Conventions/CodeConventions.doc7.html
The expressions in a for statement should be separated by blank spaces. Example: for (expr1; expr2; expr3)
Casts should be followed by a blank space. Examples: myMethod((byte) aNum, (Object) x); myMethod((int) (cp + 5), ((int) (i + 3)) + 1);
file:///E|/copy1/prashant/books/Books/Docs/Java%20Coding%20Conventions/CodeConventions.doc8.html
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
Examples
The prefix of a unique package name is always written in alllowercase 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. Packages 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.
file:///E|/copy1/prashant/books/Books/Docs/Java%20Coding%20Conventions/CodeConventions.doc8.html
Classes
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 class Raster; words-avoid acronyms and class ImageSprite; abbreviations (unless the abbreviation is much more widely used than the long form, such as URL or HTML).
Interfaces
Methods
Methods should be verbs, in mixed case with the first letter lowercase, with the first letter of each internal word capitalized.
Except for variables, all instance, class, and class constants are in mixed case with a lowercase first letter. Internal words start with capital letters. Variable names should not start with underscore _ or dollar sign $ characters, even though both are allowed. int Variable names should be short char yet meaningful. The choice of a float 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 i; c; myWidth;
Variables
file:///E|/copy1/prashant/books/Books/Docs/Java%20Coding%20Conventions/CodeConventions.doc8.html
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;
file:///E|/copy1/prashant/books/Books/Docs/Java%20Coding%20Conventions/CodeConventions.doc9.html
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.
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.
file:///E|/copy1/prashant/books/Books/Docs/Java%20Coding%20Conventions/CodeConventions.doc9.html
} 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; should be written as a = b + c; d = a + r; // AVOID!
file:///E|/copy1/prashant/books/Books/Docs/Java%20Coding%20Conventions/CodeConventions.doc9.html
return booleanExpression; Similarly, if (condition) { return x; } return y; should be written as return (condition ? x : y); 10.5.3 Expressions before `?' in the Conditional Operator If an expression containing a binary operator appears before the ? in the ternary ?: operator, it should be parenthesized. Example: (x >= 0) ? x : -x; 10.5.4 Special Comments Use XXX in a comment to flag something that is bogus but works. Use FIXME to flag something that is bogus and broken.
file:///E|/copy1/prashant/books/Books/Docs/Java%20Coding%20Conventions/CodeConventions.doc10.html
[Contents] [Prev]
11 - Code Examples
11.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. For more information, see "Class and Interface Declarations" on page 4 and "Documentation Comments" on page 9 /* * @(#)Blah.java 1.82 99/03/18 * * Copyright (c) 1994-1999 Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, California, 94303, U.S.A. * All rights reserved. * * This software is the confidential and proprietary information of Sun * Microsystems, Inc. ("Confidential Information"). You shall not * disclose such Confidential Information and shall use it only in * accordance with the terms of the license agreement you entered into * with Sun. */ package java.blah; import java.blah.blahdy.BlahBlah; /** * Class description goes here. * * @version 1.82 18 Mar 1999 * @author Firstname Lastname */ public class Blah extends SomeClass { /* A class implementation comment can go here. */ /** classVar1 documentation comment */ public static int classVar1; /** * classVar2 documentation comment that happens to be * more than one line long
file:///E|/copy1/prashant/books/Books/Docs/Java%20Coding%20Conventions/CodeConventions.doc10.html (1 of 2) [8/1/02 8:29:41 AM]
file:///E|/copy1/prashant/books/Books/Docs/Java%20Coding%20Conventions/CodeConventions.doc10.html
*/ private static Object classVar2; /** instanceVar1 documentation comment */ public Object instanceVar1; /** instanceVar2 documentation comment */ protected int instanceVar2; /** instanceVar3 documentation comment */ private Object[] instanceVar3; /** * ...constructor Blah documentation comment... */ public Blah() { // ...implementation goes here... } /** * ...method doSomething documentation comment... */ public void doSomething() { // ...implementation goes here... } /** * ...method doSomethingElse documentation comment... * @param someParam description */ public void doSomethingElse(Object someParam) { // ...implementation goes here... } }
[Contents] [Prev]