You are on page 1of 15

JAVA PROGRAMMING STANDARDS

Document No: TSQM/JAVA/STD/01


Version. : 1.4
Date : 21-Sep-2002

Approved by :
(Signature)
Name

Role

Amendment Record Sheet


SNo.

Date

Amendment

1
2

4-Sep-01
28-Sep-01

10-Oct-01

2-Jun-03

Baseline Document
Document name in the footer is
changed
Spelling and grammatical
corrections
Company name has been
changed to

Approved
By

Ver. No.

Remove
Page

Insert
Page

1.0
1.1

All

All

1.2

All

All

1.3

All

All

21-Sep-02

Changes done based on the


experience gained in projects
that are executed

TSQM/JAVA/STD/01
Java Standards

JAVA CODING STANDARDS


1.4
All
All

Ver.: 1.4
Page 2 of 15

JAVA CODING STANDARDS


TABLE OF CONTENTS
1.0

Objective..................................................................................................................4

2.0

Files.........................................................................................................................4

3.0

Indentation..............................................................................................................4

4.0

Comments and Documentation..............................................................................5

5.0

Declarations............................................................................................................7

6.0

Statements...............................................................................................................8

7.0

White Spaces...........................................................................................................9

8.0

Naming Conventions............................................................................................10

I.

Packages................................................................................................................10

II.

Classes & Interfaces........................................................................................10

III.

Methods............................................................................................................10

IV.

Variables...........................................................................................................11

V.

Constants..............................................................................................................11

VI.

Objects..............................................................................................................12

VII.

Components......................................................................................................12

9.0

Miscellaneous Programming Practices...............................................................12

TSQM/JAVA/STD/01
Java Standards

Ver.: 1.4
Page 3 of 15

JAVA CODING STANDARDS

1.0

Objective
The objective of this manual is to provide a set of standards for JAVA'
Programming to produce software that is:

Maintainable

Reliable

Portable

Consistent

Re-usable

2.0

Files

3.0

When private classes and interfaces are associated with a public class, they
should be put in the same source file as the public class.
The public class should be the first class or interface in the file. All source
files should have the following comment style that lists the Class
Description, Version no, Date Created, Last Modified Date, and
Modification Log.
The comments should also include the Private class names as well as
interfaces (if any) along with their description. (Can be included in a
tabular format like the Modification Log).
/*
* Class Description:
* Hierarchy Structure
* Version No:
* Date Created:
* Last Modified Date:
* Modification Log:
* SNo | Change Date | Changed By | Change Description
* Private Class Names
*/

Indentation

Tabs must be set exactly every 4 spaces


Lines should not be longer than 80 characters

When an expression will not fit on a single line, break it according to these
general principles:
Break after a comma.
Break before an operator.

TSQM/JAVA/STD/01
Java Standards

Ver.: 1.4
Page 4 of 15

JAVA CODING STANDARDS


Align the new line after indenting 8 spaces.

Examples:
var = someMethod1(longExpression1,
someMethod2(longExpression2,
longExpression3));

longName1 = longName2 * (longName3 + longName4)


+ 4 * longname6;
//PREFER
longName1 = longName2 * (longName3 + longName4
- longName5) + 4 * longname6;
// AVOID
//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();
}

4.0

Comments and Documentation

Block comments should be used to provide descriptions of files, methods,


data structures and algorithms. Block comments should be used at the
beginning of each file and before each method. They should also be used

TSQM/JAVA/STD/01
Java Standards

Ver.: 1.4
Page 5 of 15

JAVA CODING STANDARDS


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 blank should precede a block comment line to set it apart from the rest
of the code.
/*
* Here is a block comment.
*/
Short comments should 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 (refer previous point).
if (condition)
{
/* Handle the condition. */
...

}
Very short comments should 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 code,
they should all be indented to the same tab setting.
if (a == 2)
{
return TRUE;
/* special case */
} else
{
return isPrime(a);
/* works only for odd a */
}
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.
// ...
//}
TSQM/JAVA/STD/01
Java Standards

Ver.: 1.4
Page 6 of 15

JAVA CODING STANDARDS


//else {
// return false;
//}

Documentation for the Member Functions should be of the following


style:
/*
* Method Description:
*Method Scope: (Public / Private)
* Parameters Passed:
* Returns:
* Exceptions Thrown:
*/
For
Comment
type
Documenta
tion

C style

Single line

TSQM/JAVA/STD/01
Java Standards

Usage

Example

Use documentation comments


immediately before declarations
of interfaces, classes, member
functions, and fields to
document them. Documentation
comments are processed by
javadoc, see below, to create
external documentation for a
class.
Use C-style comments to
document out lines of code that
are no longer applicable, but that
you want to keep just in case
your users change their minds, or
because you want to temporarily
turn it off while debugging.

/**
Customer A customer is
any person or organization
that we sell services and
products to.

Use single line comments


internally within member
functions to document business
logic, sections of code, and
declarations of temporary
variables.

@author S.W. Ambler


*/
/*
This code was commented
out by J.T. Kirk on Dec 9,
1997 because it was
replaced by the preceding
code. Delete it after two
years if it is still not
applicable.
. . . (the source code )
*/
// Apply a 5% discount to
all invoices
// Over $1000 as defined
by the Sarek
// Generosity campaign
started in
// Feb. of 1995.
Ver.: 1.4
Page 7 of 15

JAVA CODING STANDARDS

5.0

Declarations

6.0

Only one declaration per line should be made.


Use a space between the type and the identifier.
Always initialize the local variables in the declaration statements, unless
the initial value depends on some computation.
Always initialize static fields.
Declare all non-persistent fields as static or transient.
All declarations should be made only at the beginning of blocks, except
for loop indexes.
Class and Interface Declarations:
All descriptions of a particular class should be present in its
corresponding documentation.
No space between a method name and the parenthesis "(" starting
its parameter list
Sample(int i, int j)
{
ivar1 = i;
ivar2 = j;
}
Open and Close braces should appear at new lines. (i.e., opening
braces should not be placed at the end of the declaration statement
and the close braces should not be put at the end of a block)
A Blank Line should separate methods.

Statements

Each line should have only one statement.


argv++;
// Correct
argc--;
// Correct
argv++; argc--;
// AVOID!
Compound Statements:
The enclosed statements should be indented one more level than
the compound statement.
Open and Close braces should appear at new lines. (i.e., opening
braces should not be placed at the end of the declaration statement
and the close braces should not be put at the end of a block)
Braces are used around all statements; even single statements,
when they are part of a control structure, such as an if-else or
for statement. This makes it easier to add statements without
accidentally introducing bugs due to forgetting to add braces.

TSQM/JAVA/STD/01
Java Standards

Ver.: 1.4
Page 8 of 15

7.0

JAVA CODING STANDARDS


Return statements should not have parenthesis around the values, unless it
is an expression, in which case the expression should always be enclosed
by parenthesis.
The if, if-else, and if-else-if statements should always have parenthesis
even if the block has only one statement.
For statements should only have a maximum of 2 variables in the initialize
or Update clause, incase more required, use separate for statements. The
automatic variables should be defined in the for statement itself.
Eg:
for (int i=0, int j=1; i<10, ,j<20; i++, j++)
{
..
}
while, try-catch and do-while statements should have parenthesis even if
only 1 statement occurs in the body of the block.
A switch statement should have a Default case and a Break statement
should be given for the Default case also.
The use of do while loops should be avoided. There are two reasons for
this guideline. First, the construct is superfluous. Any statement that can
be written as a do while loop can equally be written as a while loop or a
for loop. Complexity is avoided by simply reducing the number of
constructs being used. Second, is for readability as a loop with the
conditional part at the end is more difficult to read than one with the
conditional construct at the beginning.

To improve the understandability of code use parenthesis to specify the


exact order of operations in Java code. The order of operations for a
language, need not be known, to understand source code.
Type conversions must always be done explicitly. Never rely on implicit
type
floatValue = (float) intValue; // NOT: floatValue = intValue;
By using this guideline, the developer indicates that he or she is aware
of the different types referenced and that the mix is intentional.

White Spaces

TSQM/JAVA/STD/01
Java Standards

Ver.: 1.4
Page 9 of 15

JAVA CODING STANDARDS

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.

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:
a += c + d;
a = (a + b) / (c * d);
while (d++ = s++)
{
n++;
}
printSize("size is " + foo + "\n");

8.0

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);

Naming Conventions
I. Packages
The packages should be named with the prefix of meaningful names and
then followed by the class name in lower case.
Example:
patientcare.fileoperations
drug.dbconnect

TSQM/JAVA/STD/01
Java Standards

Ver.: 1.4
Page 10 of 15

JAVA CODING STANDARDS


The import statements must follow the package statement. import
statements should be sorted with the most fundamental packages first then
grouped with associated packages together with one blank line between
groups.
import java.io.*;
import java.net.*;
import javax.swing.*;
import javax.swing.event.*;
import org.linux.apache.server.*;
The import statement location is enforced by the Java language. The
sorting of the different import statements by group facilitates the browsing
of the list when there are many imports and makes it easier to determine
upon which packages the existing package is designed. The grouping
reduces complexity by collapsing related information into a common unit.
II. Classes & Interfaces
Class/Interface names should be nouns, in mixed case with the first
letter of each internal word capitalized. Class/Interface names should be
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). The letter I should prefix interface
names.
class
Raster;
class ImageSprite;
interface
IRasterDelegate;
interface IStoring;
Exception classes should be suffixed with Exception.
class AccessException
{

}
Exception classes are not precisely part of the main architecture of a
program and naming them in this manner enables them to stand out
relative to the other classes.
III. Methods
Methods should be verbs, in mixed case with the first letter
lowercase, with the first letter of each internal word capitalized. All
private variables whose values might be set or used by external programs
should have SET and GET methods, to set and read the value respectively.
TSQM/JAVA/STD/01
Java Standards

Ver.: 1.4
Page 11 of 15

JAVA CODING STANDARDS


And all boolean variables whose value is checked should have a IS
method associated with it.
run();
runFast();
getBackground();
getPtnName();
setPtnId();
isPtnExist();
IV. Variables
Internal words should start with capital letters. Variable names
should not start with underscore _ or dollar sign $ characters,
even though both are allowed.
Use full English Descriptors that accurately describe the
variable/field
Avoid names that are similar or differ only in case. For example
the variable names persistentObject and persistentObjects
should not be used together, nor should anSqlDatabase and
anSQLDatabase
Capitalize the first letter of standard acronyms. Names will often
contain standard abbreviations, such as SQL for Standard Query
Language. Names such as sqlDatabase for an attribute, or
SqlDatabase for a class, are easier to read than sQLDatabase and
SQLDatabase.
Variable names must be in mixed case starting with lower case. For
e.g. line, filePrefix
Collections, such as an array or a vector, should be given a
pluralized name representing the types of objects stored by the
array.
The name should be a full English descriptor with the first letter of
all non-initial words capitalized.
Examples :
Customers
OrderItems
Negated boolean variable names must be avoided.
boolean isError; // NOT: isNotError
boolean isFound; // NOT: isNotFound
The problem manifests itself when logical not operators are used
and double negative arises. At first glance, it is not apparent what !
isNotEror means.
Acronyms should not be uppercase when used as name.
exportHtmlSource(); // NOT: exportHTMLSource();
Using all uppercase for the base name will give conflicts with the
naming conventions given above. A variable of this type would
have to be named dVD, hTML, etc. which obviously is not very
readable. Another problem illustrated in the examples above:
TSQM/JAVA/STD/01
Java Standards

Ver.: 1.4
Page 12 of 15

JAVA CODING STANDARDS


When the name is connected to another, the readability is seriously
reduced. The word following the acronym does not stand out as it
should.
Generic variables should have the same name as their type
For e.g. void setTopic(Topic topic); // NOT: void setTopic(Topic
value)
All names should be written in English.
filename; // NOT: filNam
English is the preferred language for international development.
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/ loop invariant variables . Common names for temporary
variables are tempi, tempj, tempk, tempm, and tempn for integers;
c, d, and e for characters.
The variable names should be preceded by the Scope Descriptor
and the Variable Type.
Scope Descriptor:
l
Local/Method level
c
Class Level
p
Parameter passed in Methods
Variable Type:
int
i
char
c
float
f
double
d
boolean
boo
byte
by
short
sh
long
l
array
a
String
S
StringBuffer SB
Integer
I
Character
C
Float
F
Long
L
Double
D
Byte
BY
Short
SH
Boolean
BOO
Examples:
int liCount; local int variable
char ccName; class level character variable

TSQM/JAVA/STD/01
Java Standards

Ver.: 1.4
Page 13 of 15

JAVA CODING STANDARDS


float pfWidth; float type parameter variable
int liaNos; local integer array
V. Constants
The names of variables declared class constants and of ANSI
constants should be all uppercase with words separated by underscores
("_").
static final int MIN_WIDTH = 4;
static final int MAX_WIDTH = 999;
static final int GET_THE_CPU = 1;
VI. Objects
The instantiated objects of any class should be prefixed with obj
followed by the Class name and suffixed by the sequence no, denoting that
its the nth object of the same class.
objRaster1, objRaster2.
VII. Components
The component names should be prefixed as follows:
Label
lbl
TextBox
txt
TextArea
txa
Button
btn
CheckBox
chk
CheckBoxGroup
chg
Choice
cho
List
lst
Scrollbar
scb
Menu
mnu
MenuBar
mnb
MenuItem
mni
Layout
lay
Panel
pnl
Frame
fra
Dialog
dlg
Applet
app
JApplet
JApp
JButton
JBtn
JCheckBox
JChk
JComboBox
JCbo
JLabel
JLbl
JRadioButton
JRad
JScrollPane
JScr
JTabbedPane
JTab
JTable
JTbl
JTextField
JTxt
TSQM/JAVA/STD/01
Ver.: 1.4
Java Standards
Page 14 of 15

JTree

9.0

JAVA CODING STANDARDS


JTre

Miscellaneous Programming Practices

Don't make any instance or class variable public without good reason.
Use local variables for performing only one functionality, avoid reuse.
Numerical constants (literals) should not be coded directly, except for -1,
0, and 1, which can appear in a for loop as counter values. For others
constants should be used.
Avoid assigning several variables to the same value in a single statement.
Import only the classes required form a package instead of importing the
whole package.
Eg:
Instead of
import java.util.*;
Use the following:
import java.util.HashTable;
When checking for equality against a constant value, have the constant
value on the RightHandSide of the equality check statement.
Eg:
Instead of
(ABC).equals(Str)
use the following:
(Str).equals(ABC)
In for statements, when checking the automatic values against other
values, assign those values to variables and use those variables in the
checks.
Eg:
Instead of:
Vector v = new Vector();
for (int i=0; i < v.length(); i++)
{

}
use the following:
Vector v= new Vector();
int length = v.length();
for (int i=0; i< length; i++)
{

TSQM/JAVA/STD/01
Java Standards

Ver.: 1.4
Page 15 of 15

You might also like