You are on page 1of 25

Standard for Java Coding Revision: 1.0 Author: N Carlyle Effective Date: 2004-08-24 CONTENTS Notice 2 Approval 2 Foreword 2 1.

Introduction 5 2. Scope 5 3. File suffixes and names 5 3.1. File suffixes 5 3.2. File names 5 4. Source file organisation 6 4.1. General 6 4.2. Java source files 6 4.2.1. General 6 4.2.2. Beginning comments 6 4.2.3. Package and import statements 4.3. Class and interface declarations 4.4. Indentation 7 4.5. Line length 7 4.6. Wrapping lines 7 5. Comments 9 5.1. Introduction 9 5.2. Implementation comment formats 5.2.1. Block comments 9 5.2.2. Single-line comments 10 5.2.3. Trailing comments 10 5.2.4. End-of-line comments 10 5.3. Documentation comments 11 6. Declarations 11 6.1. Number per line 11 6.2. Initialisation 11 6.3. Placement 12 6.4. Declaring member variables 12 6.5. Class and interface declarations 6.6. Member method declarations 14 7. Statements 14 7.1 General 14 7.2 Simple statements 14 7.3. Compound statements 14 7.4. return Statements 15 7.5. if-else class of Statements 15 7.6. for Statements 16 7.7. while Statements 16 7.8. do-while Statements 16 7.9. switch Statements 16 7.10. try-catch Statements 17

6 6

9

12

8. White space 17 8.1 Blank lines 17 8.2 Blank spaces 17 9. Naming conventions 18 10. Programming practices 19 10.1 Providing access to instance and class variables 19 10.2. Referring to class variables and methods 19 10.3. Constants 19 10.4. Variable assignments 20 10.5. Miscellaneous practices 20 10.5.1. Parentheses 20 10.5.2. Returning values 20 10.5.3. Expressions before ‘?’ in the conditional operator 10.5.4. Special comments 21 11. Java source file example 21 12. Javadoc - The Java API Documentation Generator - overview 12.1 Description 22 12.2. Javadoc commenting the source code 22 12.3. Standard HTML 23 12.4. Javadoc tags 23 12.5. Options 24 12.6. Examples 25 Annex A : Abbreviations and definitions 27 A.1 Abbreviations 27 A.2 Definitions 27 TABLES Table Table Table Table Table Table Table 1: 2: 3: 4: 5: 6: 7: Java file suffixes 5 Java file names 5 Order of class or interface declarations in Java Java naming conventions 18 Javadoc tags 23 Javadoc options 24 Options Provided by Standard doclet 25

21 22

7

1. Introduction Before you can produce great program code you need to have a process for writing great code. That is the aim of any programming language standard. In a large organisation such as SITA, it is especially important to have same basic programming standards and they are important to programmers for a number of reasons: a) hardly any software is maintained for its whole life by the original author; b) 80% of the lifetime cost of a piece of software goes to maintenance; c) programming standards improve the readability of the software, allowing programmers to understand new code more quickly and thoroughly, thus saving costly programmer time; d) 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; e) it improves the readability, consistency, and uniformity of the code, which makes it easier to understand and maintain; f) it makes the code easier to trace and debug, because it is clear and consistent; g) it allows you to continue more easily where you or another programmer stopped, particularly after a long period of time; and

h) it increases the benefit of code walkthroughs, because the participants can focus more on what the code is doing. Writing Java with a good standard is not hard, but it does require attention to detail. For the standards to work, every programmer must conform to the programming standards. 2. Scope This document contains the official conventions (for all hardware/software platforms) as defined by Sun Microsystems Inc., the license authority for Java, as reflected at their Java Programming conventions Web site (http://Java.sun.com/docs/codeconv/) as at 14th March 2003. The intention of these conventions is to make code readable, therefore portable, to all developers. There should be no problem conforming as they make sense and are not rigid. 3. File suffixes and names 3.1. File suffixes Java software uses the following file suffixes: Table 1: Java file suffixes File type Suffix Java source file .java Java bytecodes file .class Should the developer be using a GUI development package, it may have other file types as specified by the package vendor (e.g. .prj for Project files etc.). 3.2. File names Frequently used file names include: Table 2: Java file names File name Use GNUmakefile The preferred name for makefiles README The preferred name for a file that summarises the contents of a particular directory For information on makefiles, see “http://geosoft.no/javamake.html” 4. Source file organisation 4.1. General A Java source file consists of sections, separated by blank lines and optional comments identifying each section. Avoid files longer than 2000 lines as they are cumbersome to work with. The Object Oriented paradigm dictates that you should be creating reusable code. This would tend to imply that programs would consist of many small files of reusable code, tied together by a main method. For an example of a Java program properly formatted, see "Java source file example”. 4.2. Java source files 4.2.1. General 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: Beginning comments (see "Beginning comments” below);

Package and Import statements; then Class and interface declarations (see "Class and interface declarations" below). 4.2.2. Beginning comments All source files should begin with a C-style comment that lists the class name, version information, date, and copyright notice: A.1.1.1 /* A.1.1.2 Classname A.1.1.3 * A.1.1.4 Version information A.1.1.5 * A.1.1.6 Date A.1.1.7 * A.1.1.8 Copyright notice A.1.1.9 */ 4.2.3. Package and import statements The first non-comment line of most Java source files is a package statement. After that, import statements can follow. A.1.1.10 package Java.awt; A.1.1.11 A.1.1.12 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. 4.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” in Annex B for an example that includes comments. Table 3: Order of class or interface declarations in Java Part of class/interface declaration Notes Class/interface documentation comment (/**...*/) See "Documentation comments" below for information on what should be in this comment. Class or interface statement Class/interface implementation comment (/*...*/), if necessary This comment should contain any class-wide or interface-wide information that was not appropriate for the class/interface documentation comment. See “implementation comment formats”. Class (static) variables First, the public class variables, then the protected, then package level (no access modifier), and then the private. Instance variables First public, then protected, then package level (no access modifier) and then private. Constructors Remember that there will not be a default constructor, (also called the no-arg constructor), if you define your own constructors Methods Group methods 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 4.4. Indentation Use four spaces as the unit of indentation. The exact construction of the indentation (spaces vs. tabs) is your choice. When used set tabs every four spaces.

4.5. Line length Do not use lines longer than 80 characters, since many terminals do not handle them well, or force you to scroll right and left to see the code. NOTE: Examples for use in documentation should have a shorter line length generally no more than 70 characters. 4.6. Wrapping lines When an expression will not fit on a single line, break it according to the following general principles: a) break after a comma; b) break before an operator; c) prefer higher-level breaks to lower-level breaks; d) align the new line with the beginning of the expression at the same level on the previous line; and e) if the above rules lead to confusing code or to code that is squashed up against the right margin, just indent eight spaces (2 tabs) instead. Here are some examples of breaking method calls: A.1.1.13 someMethod(longExpression1, longExpression2, longExpression3, A.1.1.14 longExpression4, longExpression5); A.1.1.15 A.1.1.16 var = someMethod1(longExpression1, A.1.1.17 someMethod2(longExpression2, A.1.1.18 (longExpression3); Following are two examples of breaking an arithmetic expression. The first is preferred, since the break occurs outside the parenthesised expression, which is at a higher level. A.1.1.19 longName1 = longName2 * (longName3 + longName4 - longName5) A.1.1.20 + 4 * longname6; // PREFER A.1.1.21 A.1.1.22 longName1 = longName2 * (longName3 + longName4 A.1.1.23 - 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 (2 tabs). Conventional indentation: A.1.1.24 someMethod(int anArg, Object anotherArg, String yetAnotherArg, A.1.1.25 Object andStillAnother) A.1.1.26 { A.1.1.27 ... A.1.1.28 } Indent eight spaces (2 tabs) to avoid very deep indents A.1.1.29 private static synchronized horkingLongMethodName(int anArg, A.1.1.30 Object anotherArg, String yetAnotherArg, A.1.1.31 Object andStillAnother) A.1.1.32 { A.1.1.33 ... A.1.1.34 } For if statements that wrap to the next line use eight-space (2 tabs), as conventional four–space (1 tab) indentation makes seeing the body difficult. Do not use this indentation A.1.1.35 if ((condition1 && condition2)

A.1.1.36 || (condition3 && condition4) A.1.1.37 ||!(condition5 && condition6)) A.1.1.38 { // BAD WRAPS A.1.1.39 doSomethingAboutIt(); // MAKE THIS LINE EASY TO MISS A.1.1.40 } Use this indentation instead A.1.1.41 if ((condition1 && condition2) A.1.1.42 || (condition3 && condition4) A.1.1.43 ||!(condition5 && condition6)) A.1.1.44 { A.1.1.45 doSomethingAboutIt(); A.1.1.46 } Or use this A.1.1.47 if ((condition1 && condition2) || (condition3 && condition4) A.1.1.48 ||!(condition5 && condition6)) A.1.1.49 { A.1.1.50 doSomethingAboutIt(); A.1.1.51 } Here are three acceptable ways to format ternary expressions: A.1.1.52 alpha = (aLongBooleanExpression) ? beta : gamma; A.1.1.53 A.1.1.54 alpha = (aLongBooleanExpression) ? beta A.1.1.55 : gamma; A.1.1.56 A.1.1.57 alpha = (aLongBooleanExpression) A.1.1.58 ? beta A.1.1.59 : gamma; 5. Comments 5.1. Introduction Java programs can have two kinds of comments: implementation comments and documentation comments. Implementation comments are the same as those found in C++, and use /*...*/, and //, as delimiters. Use implementation comments for commenting out code or for comments about the particular implementation. Doc comments are Java-only and use /**...*/ as delimiters. The Javadoc, tool extracts the doc comments to HTML files. Use doc comments to describe the specification of the code from an implementation-free perspective. The way that you document your code with comments has a huge impact both on your own productivity and on the productivity of everyone else that later maintains and enhances it. By commenting your code early in the development process you become more productive because it forces you to think through your logic before you commit it to code. Furthermore, when you revisit code that you wrote days or weeks earlier you can easily determine what you were thinking when you wrote it – it is documented for you already. Developers who might not necessarily have the source code at hand read the comments to quickly find out what the code is doing. Use comments 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 to build the corresponding package or in what directory it resides should not be included as a comment. Discussions of non-trivial or non-obvious design decisions are 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. Do not enclose comments in large boxes drawn with asterisks or other characters. Never include special characters such as form-feed and backspace. 5.2. Implementation comment formats Programs can have four styles of implementation comments: block, single-line, trailing and end-of-line. 5.2.1. Block comments Use clock comments to provide descriptions of files, methods, data structures and algorithms. Use them at the beginning of each file and before each method and other places, such as within methods. Indent block comments inside a method to the same level as the code they describe. To set it apart from the rest of the code, a blank line should precede a block comment. A.1.1.60 /* A.1.1.61 * Here is a block comment. A.1.1.62 * That explains the code A.1.1.63 */ Block comments that start with /*-, are recognised by indent(1) as the beginning of a block comment that should not be reformatted. A.1.1.64 /*A.1.1.65 * Here is a block comment with some very special A.1.1.66 * indent(1) ignores the formatting below A.1.1.67 * A.1.1.68 * one A.1.1.69 * two A.1.1.70 * three A.1.1.71 */ NOTE: If you do not use indent(1), you do not have to use /*- in your code or make any other concessions to the possibility that someone else might run indent(1) on your code. 5.2.2. Single-line comments Short comments can appear on a single line indented to the level of the code that follows it. Comment that overflows to another line should follow the block comment format (see “Block comments”). A blank line should precede a single-line comment. Here is an example of a single-line comment in Java code (also see "Documentation comments"). A.1.1.72 if (condition) A.1.1.73 { A.1.1.74 /* Handle the condition. */ A.1.1.75 ... A.1.1.76 } 5.2.3. Trailing comments Very short comments can appear on the same line as the code they describe, but shifted far enough to separate them from the statements. If more than one short comment appears in a chunk of code, indent them to the same tab setting. Here is an example of a trailing comment in Java code: A.1.1.77 if (2 == a) A.1.1.78 { A.1.1.79 return TRUE; /* special case */ A.1.1.80 } A.1.1.81 else A.1.1.82 { A.1.1.83 return isPrime(a); /* works only for odd a */ A.1.1.84 } Trailing comments should very rarely be required

5.2.4. End-of-line comments The // comment delimiter can comment out a complete line or only a partial line. It should not 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: A.1.1.85 if (1 < foo) A.1.1.86 { A.1.1.87 // Do a double flip. A.1.1.88 ... A.1.1.89 } A.1.1.90 else A.1.1.91 { A.1.1.92 return false; // Explain why here. A.1.1.93 } A.1.1.94 //if (1 < bar) A.1.1.95 //{ A.1.1.96 // A.1.1.97 // // Do a triple-flip. A.1.1.98 //... A.1.1.99 //} A.1.1.100 //else { A.1.1.101 // return false; A.1.1.102 //} 5.3. Documentation comments Documentation comments (referred to as doc comments in the literature) describe java classes, interfaces, constructors, methods, and variables. Each doc comment is set inside the comment delimiters /**...*/, with one comment per class, interface, or method. This comment should appear just before the declaration: A.1.1.103 /** A.1.1.104 *The Example class provides ... A.1.1.105 */ A.1.1.106 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 one space of indentation (to vertically align the asterisks). Members, including constructors, have four spaces for the first doc comment line and five spaces thereafter. If you need to give information about a class, interface, variable, or method that is not appropriate for doc, use an implementation block comment or singleline 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. Place doc comments immediately before, class, interface, constructor, method or variable declarations for them to be recognized by javadoc. Javadoc associates doc comments with the first declaration after the comment. Therefore, you should never position doc comments inside a method or constructor definition block. A brief summary of Javadoc can be found in “Javadoc summary“ For further details, see “Javadoc tool home page” and "Javadoc – The API Documentation Generator” which includes information on the doc comment tags (both on http://java.sun.com). 6. Declarations 6.1. Number per line One declaration per line is recommended since it encourages commenting. In other words: A.1.1.107 int level; // indentation level A.1.1.108 int size; // size of table

is preferred over A.1.1.109 int level, size; Do not put different types on the same line. A.1.1.110 int foo, fooarray[]; // WRONG! NOTE: The examples above use one space between the type and the identifier. Another acceptable alternative (and more preferable) is to use tabs or multiple spaces to improve readability. A.1.1.111 int level; // indentation level A.1.1.112 int size; // size of table A.1.1.113 Object currentEntry; // currently selected table entry 6.2. Initialisation Try to initialise local variables where they are declared. The only reason not to initialise a variable where it is declared is if the initial value depends on some computation occurring later in the program. 6.3. Placement Restrict declarations to the beginning of blocks (a block is any code surrounded by curly braces "{" and "}"). Do not wait to declare variables until their first use; it can confuse the unwary programmer and hamper code portability within the scope. A.1.1.114 void myMethod() A.1.1.115 { A.1.1.116 int int1 = 0; // beginning of method block A.1.1.117 A.1.1.118 if (condition) A.1.1.119 { A.1.1.120 int int2 = 0; // beginning of "if" block A.1.1.121 ... A.1.1.122 } // end of “if” block A.1.1.123 } // end of method block The exceptions to the rule are indexes of for loops (throwaway variables), which in Java can be declared in the for statement: A.1.1.124 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: A.1.1.125 int count; A.1.1.126 ... A.1.1.127 myMethod() A.1.1.128 { A.1.1.129 if (condition) A.1.1.130 { A.1.1.131 int count = 0; // AVOID! A.1.1.132 ... A.1.1.133 } A.1.1.134 ... A.1.1.135 } 6.4. Declaring member variables For reasons of encapsulation, do not declare variables in your classes as public. If they are declared protected, there is the possibility of member methods in subclasses accessing them directly, which increases the coupling within a class hierarchy. As this makes your classes more difficult to maintain and enhance, avoid the problem by making your variable private. Use public ‘setter’ and ‘getter’ accessor methods and private variables.

6.5. Class and interface declarations A doc comment that includes a description of the class or interface, the version number and the author must precede the declaration of the class or interface declaration. Each method, including constructors in the class or interface shall also be preceded by a doc comment. Running your class or interface through Javadoc will produce the documentation necessary for other users to use those classes and interfaces. When coding Java classes and interfaces, use the following formatting rules: a) no space between a method name and the parenthesis "(" starting its parameter list; b) open brace "{" may: i) appear at the end of the same line as the declaration statement; or ii) appear on a line by itself indented to match the corresponding opening statement; and c) closing brace "}" may: i) appear on a line by itself indented to match its corresponding opening statement; or ii) appear on a line by itself indented to match the corresponding opening brace; except iii) when it is a null statement the closing brace "}" should appear immediately after the opening brace "{". Whichever layout of b) and c) above that you choose, use it consistently. A.1.1.136 A.1.1.137 A.1.1.138 A.1.1.139 A.1.1.140 A.1.1.141 A.1.1.142 A.1.1.143 A.1.1.144 A.1.1.145 A.1.1.146 A.1.1.147 A.1.1.148 A.1.1.149 A.1.1.150 A.1.1.151 A.1.1.152 A.1.1.153 A.1.1.154 A.1.1.155 A.1.1.156 A.1.1.157 A.1.1.158 A.1.1.159 A.1.1.160 A.1.1.161 A.1.1.162 or A.1.1.163 A.1.1.164 A.1.1.165 A.1.1.166 A.1.1.167 A.1.1.168 package Prop; import java.util.*; /** * Lists system information on current machine. * @author Bruce Eckel * @version 1.0 ccyy-mm-dd */ public class Property { /** Sole entry point to class & application * @param args array of string arguments * @return No return value * @exception exceptions No exceptions thrown */ public static void main(String[] args) { System.out.println(new Date()); Properties p = System.getProperties(); p.list(System.out); System.out.println("--- Memory Usage:"); Runtime rt = Runtime.getRuntime(); System.out.println("Total Memory = " + rt.totalMemory() + " Free Memory = " + rt.freeMemory()); } } package Prop; import java.util.*; /** * Lists system information on current machine. * @author Bruce Eckel * @version 1.0 ccyy-mm-dd

A.1.1.169 */ A.1.1.170 A.1.1.171 public class Property A.1.1.172 { A.1.1.173 /** Sole entry point to class & application A.1.1.174 * @param args array of string arguments A.1.1.175 * @return No return value A.1.1.176 * @exception exceptions No exceptions thrown A.1.1.177 */ A.1.1.178 A.1.1.179 public static void main(String[] args) A.1.1.180 { A.1.1.181 System.out.println(new Date()); A.1.1.182 Properties p = System.getProperties(); A.1.1.183 p.list(System.out); A.1.1.184 System.out.println("--- Memory Usage:"); A.1.1.185 Runtime rt = Runtime.getRuntime(); A.1.1.186 System.out.println("Total Memory = " A.1.1.187 + rt.totalMemory() A.1.1.188 + " Free Memory = " A.1.1.189 + rt.freeMemory()); A.1.1.190 } A.1.1.191 } 6.6. Member method declarations For a good design where you want to minimize the coupling between classes, the general rule is to be as restrictive as possible when setting the visibility of a member method. If a method does not have to be public, the make it protected, and if it does not have to be protected, then make it private. Separate methods with a blank line, and include doc comments for your methods, particularly to cater for the reusability of your classes. Define ‘setter’ and ‘getter’ accessor methods to access the variables in your class. It is always a good idea to use the orthodox canonical class form whenever you declare a class that may be used by others (which should be the rule not the exception). This means always including declarations for: A.1.1.192 A default constructor (); A.1.1.193 An equals () – that takes a parameter of type Object; A.1.1.194 A hashcode () A.1.1.195 A toString (); A.1.1.196 A clone () - and implement Cloneable; A.1.1.197 Implement Comparable; and A.1.1.198 Implement Serializable. 7. Statements 7.1 General It is a good idea to use parenthesis i.e. (and) around your test conditions in all statements that have conditions even if they do not appear to be necessary to you. Place constants on the left side of your expressions: assignments, boolean and otherwise statements. A.1.1.199 if (6 == argc) instead of: A.1.1.200 if (argc == 6) This technique can catch equality (versus assignment) errors. 7.2 Simple statements Each line should contain at most one statement. A.1.1.201 argv++; // Correct A.1.1.202 argc--; // Correct A.1.1.203 argv++; argc--; // AVOID! 7.3. Compound statements

Compound statements are statements that contain lists of statements enclosed in braces "{statements}". See the following sections for examples: a) use braces around all statements; even single statements, when they are part of a control structure, such as an if-else or for statement etc. This makes it easier to add statements without accidentally introducing bugs due to forgetting to add braces; b) the enclosed statements should be indented one more level than the compound statement; c) the opening brace may be: i) at the end of the line that begins the compound statement; or ii) it may be the only character on the next line indented to the beginning of the compound statement; and d) the closing brace will always begin on a new line and be indented to either: i) the beginning of the compound statement; or ii) opening brace. A.1.1.204 if (args[0].equals("before")) { A.1.1.205 System.out.println("gc():"); A.1.1.206 System.gc(); A.1.1.207 System.out.println("runFinalization():"); A.1.1.208 System.runFinalization(); A.1.1.209 } or A.1.1.210 if (args[0].equals("before")) A.1.1.211 { A.1.1.212 System.out.println("gc():"); A.1.1.213 System.gc(); A.1.1.214 System.out.println ("runFinalization():"); A.1.1.215 System.runFinalization(); A.1.1.216 } 7.4. return Statements A return statement with a value should not use parentheses unless they make the return value more obvious in some way. A.1.1.217 return; A.1.1.218 A.1.1.219 return myDisk.size(); A.1.1.220 A.1.1.221 return (size ? size : defaultSize); 7.5. if-else class of Statements The if-else class of statements (which are the if, if-else, if- else-if -else statements) should have the following form: A.1.1.222 if (condition) // plain if statement A.1.1.223 { A.1.1.224 statements; A.1.1.225 } A.1.1.226 A.1.1.227 if (condition) // if-else statement A.1.1.228 { A.1.1.229 statements; A.1.1.230 } A.1.1.231 else A.1.1.232 { A.1.1.233 statements; A.1.1.234 } A.1.1.235 A.1.1.236 if (condition)

A.1.1.237 { A.1.1.238 statements; A.1.1.239 } A.1.1.240 else if (condition) // else-if statement A.1.1.241 { A.1.1.242 statements; A.1.1.243 } A.1.1.244 else A.1.1.245 { A.1.1.246 statements; A.1.1.247 } NOTE: if statements always use braces {}. Should further statements be required to be executed dependent on the condition, the braces would become compulsory and could inadvertently be omitted and the code would be incorrect. Make your code future-proof. Avoid the following error-prone form: A.1.1.248 if (condition) // AVOID! this omits the braces {}! A.1.1.249 statement; A.1.1.250 7.6. for Statements A for statement should have the following form: A.1.1.251 for (initialisation; condition; update) A.1.1.252 { A.1.1.253 statements; A.1.1.254 } An empty for statement (one in which all the work is done in the initialisation, condition and update clauses) should have the following form: A.1.1.255 for (initialisation; condition; update); When using the comma operator in the initialisation 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 initialisation clause) or at the end of the loop (for the update clause). 7.7. while Statements A while statement should have the following form: A.1.1.256 while (condition) A.1.1.257 { A.1.1.258 statements; A.1.1.259 } An empty while statement should have the following form: A.1.1.260 while (condition); 7.8. do-while Statements A do-while statement should have the following form: A.1.1.261 Do A.1.1.262 { A.1.1.263 statements; A.1.1.264 } A.1.1.265 while (condition); 7.9. switch Statements A switch statement should have the following form: A.1.1.266 switch (condition) A.1.1.267 { A.1.1.268 case ABC: A.1.1.269 statements; A.1.1.270 /* falls through */ A.1.1.271 A.1.1.272 case DEF: A.1.1.273 statements;

A.1.1.274 break; A.1.1.275 A.1.1.276 case XYZ: A.1.1.277 statements; A.1.1.278 break; A.1.1.279 A.1.1.280 default: A.1.1.281 statements; A.1.1.282 break; A.1.1.283 } 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 you later add another case. 7.10. try-catch Statements A try-catch statement should have the following format: A.1.1.284 try A.1.1.285 { A.1.1.286 statements; A.1.1.287 } A.1.1.288 catch (ExceptionClass e) A.1.1.289 { A.1.1.290 statements; A.1.1.291 } A finally which executes regardless of whether or not the try block has completed successfully can also follow a try-catch statement, A.1.1.292 try A.1.1.293 { A.1.1.294 statements; A.1.1.295 } A.1.1.296 catch (ExceptionClass e) A.1.1.297 { A.1.1.298 statements; A.1.1.299 } A.1.1.300 finally A.1.1.301 { A.1.1.302 statements; A.1.1.303 } 8. White space 8.1 Blank lines Blank lines improve readability by setting off sections of code that are logically related. Always use two blank lines should in the following circumstances: a) between sections of a source file; and b) between class and interface definitions. Always use one blank line in the following circumstances: a) between methods; b) between the local variables in a method and its first statement; c) before a block (see “section 6.1.1”) or single-line (see “section 6.1.2”) comment; and d) between logical sections inside a method to improve readability. 8.2 Blank spaces

Use blank space/s in the following circumstances: a) A keyword followed by a parenthesis should be separated by a space; A.1.1.304 while (true) A.1.1.305 { A.1.1.306 ... A.1.1.307 } NOTE: Do not use a blank space between a method name and its opening parenthesis. This helps to distinguish keywords from method calls. b) A blank space should appear after commas in argument lists; c) all binary operators except the dot operator “.” should be separated from their operands by spaces; A.1.1.308 i += j + k; A.1.1.309 m = (n + i) / (j * k); A.1.1.310 printSize("size is " + foo + "\n"); d) blank spaces should never separate unary operators such as unary minus, increment ("++"), and decrement ("--") from their operands; A.1.1.311 for (int i=0;i != j++;i++) A.1.1.312 { A.1.1.313 i++; A.1.1.314 System.out.println("i = " + i + " and j = " + J); A.1.1.315 --s; A.1.1.316 } A.1.1.317 System.out.println("The numbers are equal"); e) separate the expressions in a for statement by blank spaces; A.1.1.318 for (expr1; expr2; expr3) f) follow casts with a blank space. A.1.1.319 myMethod((byte) aNum, (Object) x); A.1.1.320 myMethod((int) (cp + 5), ((int) (i + 3)) + 1); 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 is a constant, package, or class - which can be helpful in understanding the code. Table 4: Java naming conventions 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 organisation's own internal naming conventions. Such conventions might specify that certain directory name components be division, department, project, machine, or login names. com.sita.saps za.saps.firearms.ver2 edu.unisa.Java.year1.examples Classes Class names should be nouns, in mixed case with the first letter of each internal word capitalised. 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 capitalised like class names.

interface RasterDelegate; interface Storing; Methods Methods should be verbs, in mixed case with the first letter lowercase, with the first letter of each internal word capitalised. run(); runFast(); getBackground(); Variables 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 an 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. Avoid one-character variable names 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 as class constants or ANSI control character constants should be all uppercase with words separated by underscores ("_"). (Avoid using ANSI constants, for ease of debugging.) static final int MIN_WIDTH = 4; static final int MAX_WIDTH = 999; static final int GET_THE_CPU = 1; 10. Programming practices 10.1 Providing access to instance and class variables Do not make any instance or class variable public without good reason. Most times, you do not have to access instance variables directly, but it often happens as a side effect of method calls. (setRate / getRate) One example of appropriate public instance variables is the case where the class is essentially a data structure, with no behaviour. In other words, if (in C/C++) you would have used a struct instead of a class, then it is appropriate to make the class's instance variables public. 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. A.1.1.321 classMethod(); // OK A.1.1.322 AClass.classMethod(); // OK A.1.1.323 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. Declaring constants makes maintenance easier when changes are required; you have only one place to change. 10.4. Variable assignments Avoid assigning several variables to the same value in a single statement. It is hard to read and you may need to change one of the values in the future, making this error prone. A.1.1.324 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. A.1.1.325 if (c = d) // AVOID!

A.1.1.326 { A.1.1.327 ... A.1.1.328 } A.1.1.329 should be written as A.1.1.330 if ((c = d) != 0) A.1.1.331 { A.1.1.332 ... A.1.1.333 } Do not use embedded assignments in an attempt to improve run-time performance. This is the job of the compiler. A.1.1.334 d = (a = b + c) + r; // AVOID! should be written as A.1.1.335 a = (b + c); A.1.1.336 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). To save time in analysing code for modification, the expression should be as clear as possible. A.1.1.337 if (a == b && c == d) // AVOID! A.1.1.338 if ((a == b) && (c == d)) // RIGHT 10.5.2. Returning values Try to make the structure of your program match the intent. A.1.1.339 if (booleanExpression) A.1.1.340 { A.1.1.341 return true; A.1.1.342 } A.1.1.343 else A.1.1.344 { A.1.1.345 return false; A.1.1.346 } should instead be written as A.1.1.347 return booleanExpression; Similarly, A.1.1.348 if (condition) A.1.1.349 { A.1.1.350 return x; A.1.1.351 } A.1.1.352 return y; should be written as A.1.1.353 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 parenthesised. A.1.1.354 (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. 11. Java source file example The following example shows how to format a Java source file containing a single public class. Format interfaces are similarly. For more information, see "Class and interface declarations" and "documentation comments". A.1.1.355 /* A.1.1.356 * @(#)Blah.Java 1.82 99/03/18 A.1.1.357 *

A.1.1.358 A.1.1.359 A.1.1.360 A.1.1.361 A.1.1.362 Sun A.1.1.363 A.1.1.364 A.1.1.365 A.1.1.366 A.1.1.367 A.1.1.368 A.1.1.369 A.1.1.370 A.1.1.371 A.1.1.372 A.1.1.373 A.1.1.374 A.1.1.375 A.1.1.376 A.1.1.377 A.1.1.378 A.1.1.379 A.1.1.380 A.1.1.381 A.1.1.382 A.1.1.383 A.1.1.384 A.1.1.385 A.1.1.386 A.1.1.387 A.1.1.388 A.1.1.389 A.1.1.390 A.1.1.391 A.1.1.392 A.1.1.393 A.1.1.394 A.1.1.395 A.1.1.396 A.1.1.397 A.1.1.398 A.1.1.399 A.1.1.400 A.1.1.401 A.1.1.402 A.1.1.403 A.1.1.404 A.1.1.405 A.1.1.406 A.1.1.407 A.1.1.408 A.1.1.409 A.1.1.410 A.1.1.411 A.1.1.412 A.1.1.413 A.1.1.414

* * * * *

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

* 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 */ 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() {

A.1.1.415 A.1.1.416

}

// ...implementation goes here...

A.1.1.417 /** A.1.1.418 * ...method doSomethingElse documentation comment... A.1.1.419 */ A.1.1.420 public void doSomethingElse() A.1.1.421 { A.1.1.422 // ...implementation goes here... A.1.1.423 } } 12. Javadoc - The Java API Documentation Generator - overview 12.1 Description Javadoc parses the declarations and doc comments in the .java source files and formats the public and protected APIs into a set of HTML pages. In addition, it produces a list of classes, a class hierarchy and an index of all APIs. As an argument to javadoc, you can pass in either a package name or a series of .java source files. By default, javadoc produces one .html file for each .java file and each package it encounters. It does this by copying the javadoc comments and other relevant information from the .java files, adding HTML tags, and saving the resulting files to the current directory. In addition, it produces a class hierarchy (tree.html) and an index for those members (AllNames.html). When javadoc parses the class and member declarations, it picks up their signatures for inclusion. You can also add further documentation by including doc comments in the source code. Javadoc also supports standard HTML within doc comments. This is useful for code samples and for formatting text. NOTE: Javadoc uses .java files, not .class files. 12.2. Javadoc commenting the source code While javadoc will automatically parse the class, interface, method and variable declarations for some of its documentation, you can add further documentation inside doc comments, including special formatting with HTML tags. Java source files can include doc comments. Doc comments begin with /** and end with */. They indicate text to be included automatically in generated documentation. The first sentence of each doc comment should be a summary sentence, containing a concise but complete description of the declared entity (class, method, constructor etc.). This sentence ends at the first period that following a blank, tab, or line terminator or at the first tag (see “Javadoc tags”): A.1.1.424 /** A.1.1.425 * This is a doc comment and this class does nothing A.1.1.426 * but show you how to place your comments. A.1.1.427 */ 12.3. Standard HTML You can embed standard HTML tags within a doc comment. However, do not use heading tags such as <h1> and <h2>, or a horizontal rule <hr>, because javadoc creates an entire structured document and these structural tags interfere with the formatting of the generated document. 12.4. Javadoc tags Javadoc parses special tags embedded within a Java doc comment. These doc tags enable you to auto generate a complete, well-formatted API from your source code. The tags start with an (@) "at" sign.

Tags must start at the beginning of a line. Keep tags with the same name together within a doc comment. For example, put all your @author tags together so javadoc can tell where the list ends. Table 5: Javadoc tags Tag Used for Purpose @author name Classes, Interfaces Indicates the author(s) of a given piece of code. One tag per author should be used. @deprecated Classes, Member Methods Indicates that the API for the class… has been deprecated and therefore should not be used any more. @throws name description A.1.1.428 replaces @ exception name description Member Methods Describes the exceptions that a member method throws. You should use one tag per exception and give the full class name for the exception. @param name description Member Methods Used to describe a parameter passed to a member method, including its type/class and its usage. Use one tag per parameter. @return description Member Methods Describes the return value, if any, of a member method. You should indicate the type/class and the potential use(s) of the return value. @since Classes, Member Methods Indicates how long the item has existed, i.e. since JDK 1.1 @see ClassName Classes, Interfaces, Member Methods, Variables Generates a hypertext link in the documentation to the specified class. You can, and probably should, use a fully qualified class name. @see ClassName#member methodName Classes, Interfaces, Member Methods, Variables Generates a hypertext link in the documentation to the specified member method. You can, and probably should, use a fully qualified class name. @version text Classes, Interfaces Indicates the version information for a given piece of code. An example of a class comment: A.1.1.429 /**

A.1.1.430 * A class representing a window on the screen. A.1.1.431 * For example: A.1.1.432 * <pre> A.1.1.433 * Window win = new Window(parent); A.1.1.434 * win.show(); A.1.1.435 * </pre> A.1.1.436 * A.1.1.437 * @see awt.BaseWindow A.1.1.438 * @see awt.Button A.1.1.439 * @version 1.2 12 Dec 2001 A.1.1.440 * @author Billy Shakespeare A.1.1.441 */ A.1.1.442 class Window extends BaseWindow { A.1.1.443 ... A.1.1.444 } An example of a variable comment: A.1.1.445 /** A.1.1.446 * The X-coordinate of the window A.1.1.447 * @see window#1 A.1.1.448 */ A.1.1.449 int x = 1263732; An example of a method comment: A.1.1.450 /** A.1.1.451 * Return the character at the specified index. An index A.1.1.452 * ranges from <tt>0</tt> to <tt>length() - 1</tt>. A.1.1.453 * @param index The index of the desired character A.1.1.454 * @return The desired character A.1.1.455 * @throws StringIndexOutOfRangeException A.1.1.456 * Occurs when the index is not in A.1.1.457 * the range <tt>0</tt> A.1.1.458 * to <tt>length() - 1</tt>. A.1.1.459 */ A.1.1.460 public char charAt(int index) { A.1.1.461 ... A.1.1.462 } 12.5. Options The Javadoc tool uses doclets to determine its output, (the default standard doclet unless a custom doclet is specified with the -doclet option.) The Javadoc tool provides a set of command-line options for use with any doclet – Table 6: Javadoc options, below describes these options The standard doclet provides an additional set of command-line options that are described below in Table 6: All option names are case-insensitive, though their arguments can be case-sensitive. The package/s specified on the command line must be in your classpath. The call format to run Javadoc from the command line is: A.1.1.463 javadoc [options] [packagenames] [sourcefiles] [classnames] [@files] The options are: Table 6: Javadoc options Option Purpose -bootclasspath <pathlist> Override location of class files loaded by the bootstrap class loader -breakiterator Compute 1st sentence with BreakIterator -classpath <pathlist> Specify where to find user class files -doclet <class> Generate output via alternate doclet

-docletpath <path> Specify where to find doclet class files -encoding <name> Source file encoding name -exclude <pkglist> Specify a list of packages to exclude -extdirs <dirlist> Override location of installed extensions -help Display command line options and exit -J<flag> Pass <flag> directly to the runtime system -locale <name> Locale to be used, e.g. en_US or en_US_WIN -overview <file> Read overview documentation from HTML file -package Show package/protected/public classes and members -private Show all classes and members -protected Show protected/public classes and members (default) -public Show only public classes and members -source <release> Provide source compatibility with specified release -sourcepath <pathlist> Specify where to find source files -subpackages <subpkglist> Specify subpackages to recursively load -verbose Output messages about what Javadoc is doing You can customise the content and format of the Javadoc tool's output by using doclets. The Javadoc tool has a default "built-in" doclet, called the standard doclet that generates HTML-formatted API documentation. You can modify or subclass the standard doclet, or write your own doclet to generate HTML, XML, MIF, RTF or whatever output format you would like. Table 7: Options Provided by Standard doclet Option Purpose -d <directory> Destination directory for output files -use Create class and package usage pages -version Include @version paragraphs -author Include @author paragraphs -docfilessubdirs Recursively copy doc-file subdirectories -splitindex Split index into one file per letter -windowtitle <text> Browser window title for the documentation -doctitle <html-code> Include title for the overview page -header <html-code> Include header text for each page

-footer <html-code> Include footer text for each page -bottom <html-code> Include bottom text for each page -link <url> Create links to javadoc output at <url> -linkoffline <url> <url2> Link to docs at <url> using package list at <url2> -excludedocfilessubdir <name1>:… Exclude any doc-files subdirectories with given name. -group <name> <p1>:<p2>:… Group specified packages together in overview page -nocomment Suppress description and tags - generate only declarations. -nodeprecated Do not include @deprecated information -noqualifier <name1>:<name2>:... Exclude the list of qualifiers from the output. -nosince Do not include @since information -nodeprecatedlist Do not generate deprecated list -notree Do not generate class hierarchy -noindex Do not generate index -nohelp Do not generate help link -nonavbar Do not generate navigation bar -quiet Do not display status messages to screen -serialwarn Generate warning about @serial tag -tag <name>:<locations>:<header> Specify single argument custom tags -taglet The fully qualified name of Taglet to register -tagletpath The path to Taglets -charset <charset> Charset for cross-platform viewing of generated documentation. -helpfile <file> Include file that help link links to -linksource Generate source in HTML -stylesheetfile <path> File to change style of the generated documentation -docencoding <name> Output encoding name 12.6. Examples A.1.1.464 javadoc -classpath /home/dhk/javasrc/src/share/java java.io Generates HTML-formatted documentation for all classes, interfaces, methods and variables in the .java source files belonging to the java.io package located below the directory specified by classpath. It looks for the source files in this location: /home/dhk/javasrc/src/share/java/java/io/ A.1.1.465 javadoc -classpath /home/dhk/javasrc/src/share/java java.io

Generates documentation for the package java.io. A.1.1.466 javadoc java.io.PrintStream.java Generates documentation for the classes java.io.PrintStream.java [or java.io.PrintStream?]. Annex B : Abbreviations and definitions B.1 Abbreviations ANSI American National Standards Institute ASCII American Standard Code for Information Interchange. A standard assignment of 7bit numeric codes to characters FAQ Frequently Asked Questions GUI Graphical User Interface HTML HyperText Mark-up Language ISO International Standards Organisation SDLC Systems Development Life Cycle SITA State Information Technology Agency Tabs Horizontal tabulation positions URL Uniform Resource Locator B.2 Definitions Term Definition argument A data item specified in a method call. binary operator An operator that has two operands. block In the Java programming language, any code between a set of matching braces{…}. bogus Counterfeit, false, fake. bytecodes Machine-independent code generated by the Java compiler (javac) and executed by the Java interpreter in the Java Virtual Machine. classpath Environment variable that provides the path that java development tools use to find user class files. doc comments Documentation comments in a java program for use by the Javadoc tool. Javadoc A tool that extracts specific program comments from a .java file and creates standard documentation in .html files. Java Virtual Machine Sun Microsystems specification for, or implementation of, a software “execution engine” that safely and compatibly executes the bytecodes in the Java class files on a microprocessor. method A function defined in a class. ternary expression An expression using a ternary operator.

ternary operator An operator that has three operands. unary operator An operator that has one operand. variable An item of data named by an identifier. A data member of a class. A field. An attribute or property.