w3resource logo


gallery w3resource

Java Coding Style Guide

Secondary Nav

Transcript

Java Coding Style Guide

<!doctype html>
<html lang="en">
<head>
<title>Java Coding Style Guide</title>
</head>
<body>
</body>
</html>

List of Contains

  • Class layout and comments
    • Files and filenames
      • File names
      • File organization
      • Beginning comments
        • Package and import statements
        • Class, interface, enum and annotation declarations
        • Annotations
    • Indentation
      • Line length
      • Wrapping lines
    • Comment
      • Comment styles
        • Single line comments
        • Block comments
        • JavaDoc comments
          • HTML tags
  • Java syntax and its layout
    • Declarations
      • Number per line
      • Placement
      • Initialization
      • Class and Interface Declarations
    • Statements
      • Simple statements
      • Compound statements
      • if, if-else, if else-if else statements
      • switch
      • try - catch
      • for loops
    • White Spac
      • Blank lines
      • Blank spaces
    • Naming conventions

Class layout and comments

This chapter describes the layout for classes, interfaces, enums and annotations. These all share a set of common properties, so they will be described together and for readability all called 'classes' here.

Files and filenames

Files longer than 2000 lines are cumbersome and should be avoided.

File names

The file must be named after the class it represents. As for most cases each file contains only one class, this is an easy naming convention. For nested or inner classes the name of the main class must be the name of the file. As names in Java are case-sensitive, the filename is case-sensitive also.

File organization

Each Java source file contains a single class or interface. Of course, this excludes inner classes as these must be defined without an (outer) class, and thus in the same file.

Java source files have the following ordering:

  • beginning comments;
  • package and import statements;
  • class and interface declarations.

Beginning comments

Beginning comments are used for licensing and copyright information only. Here at Apache, we embed the ASL 2.0 headers at the top of every file. Note that they are not according to the JavaDoc style.

Package and import statements

The first non-comment line of most Java source files is a package statement. After an empty line import statements can follow. For example:

package org.apache.ace.core.ui;

import java.awt.Frame;
import java.io.InputStream;

A few notes must be made here:

  1. Package rules. When not using an explicit package statement in your code the code still is in a package, the default package. This easily results in name clashes and as package naming should be a part of the design, always use an explicit package name. For naming rules of packages see naming conventions;
  2. Import statements need to be explicit in order to overcome name clashes. They must be grouped by name;
  3. Import order. First in this section should be the standard Java imports like: java.lang.Throwable. Second should be the Java extensions (i.e. javax), third, the third party stuff. Finally the project-specific imports should be added.

Class, interface, enum and annotation declarations

The following comment block is an example for the comment that belongs to the declaration of a class, interface, enum or annotation. The JavaDoc syntax results in the following block:

/**
 * Configuration manager. Manages the configuration of an application. Has features
 * to import and export whole configurations and notifies components that need to
 * receive settings.
 */

The following table describes the parts of a class, interface, enum or annotation declaration, in the order that they should appear.

Part of declaration Notes
documentation
class, interface, enum or annotation
According to comment block as shown above.
statement (static) variables These should be grouped by functionality rather than by scope.
instance variables These should be grouped by functionality rather than by scope.
constructors Start with the default constructor if any.
methods These methods should also be grouped by functionality rather than by scope or accessibility. E.g. a private class method can be in between two public instance methods. The goal is to make reading and understanding the code easier. When implementing an interface, group the methods that are part of the interface.
inner classes Are placed at the bottom of the file.

Annotations

Annotations for classes and methods should be done on the line directly above the class or method. They should be indented to the same level. An example:

@Manageable(description = "Starts the system.")
public void start() {
    // ...
}

Annotations for parameters can be inlined like this:

public void setValue(@Validation("x > 0 && x < 10", "Should be between 0 and 10.") int x) {
    // ...
}

Indentation

Four spaces should be used as unit of indentation. Use spaces or let your editor convert tabs to spaces as some editors might show the tabs different than they were intended! Tabs must be set exactly every 4 spaces.

Line length

There is no explicit limit for the length of a line. Make sure that the flow of the code is clear and that, when printing the file, it is well formed when using a reasonable font.

Wrapping lines

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;
  • prefer higher level breaks to lower level breaks;
  • indent the new line with a tab;
  • if the above rules lead to confusing code or to code that's squished up against the right margin, please use common sense.

Comment

Comment styles

The Java language supports three different kinds of comments:

  • single line comments;
  • block comments;
  • JavaDoc comments.

Single line comments

The compiler ignores everything from // to the end of the line. Use this style when adding a description or some kind of explanation on the same line of code or the line above.

int a; // acceleration of the car

// all names that should be searched
String[] names;

Block comments

The compiler ignores everything from /* to */. Use this style for internal comments and copyright headers.

/*
 * This code is Copyright (c) 2012 Apache Software Foundation. All rights reserved.
 * You are not allowed to remember or reproduce anything you read below.
 */

JavaDoc comments

This indicates a documentation comment (doc comment, for short). The compiler ignores this kind of comment, just like it ignores comments that use /* and */. The JavaDoc tool uses doc comments when preparing automatically generated documentation (See: JavaDoc keywords and HTML tags). Note that JavaDoc only uses this documentation when it occurs at an expected position in the file like the class definition or a member declaration.

These comments are used to provide English descriptions of the classes, interfaces, enums, annotations, methods and the description of data structures and algorithms. These comments should be used at the beginning of each class and before each method. The official JavaDoc guidelines (see references at the end of this document) should be followed, as they provide a good and clear writing style.

A method block comment looks as follows:

/**
 * Position the splitter location at a specified position.
 * This method can for instance be used when the last position
 * is stored as a preference setting for the user.
 *
 * @param position New position of divider, defined in pixels
 *     from the left of the containing window.
 * @exception org.apache.ace.units.si.exceptions.PositionException Whenever
 *     an invalid position is passed.
 * @see com.sun.java.swing.JSplitPane
 */
public void setSplitterLocation(int position) throws PositionException {

HTML tags

For class headers, method headers and member variables JavaDoc is used in order to generate API documentation. Some HTML-tags that can be used in order to make the comment blocks more readable:

Tag Short description
<p> New paragraph.
<br> Break, a carriage return. For separation of two paragraphs, usage of <p> is preferred.
<ul><li></li></ul> Unordered list of items. Each item should start with a <li> tag. Most browsers format this as a bullet list.
<code></code> Code samples. Use this when refering to class names, method names, parameter names, etc.
There is no need to embed the parameter name in the @param tag in <code> tags; this is done by JavaDoc automatically. The same holds for the exception name in the @exception or @throws tag. In the clarifying text however, use the <code> tags when refering to parameter names etc. The example below shows the <code> tag being used for the array parameter in the text, but not in its definition.

Example:

/**
 * Prints a range from an object array. The range
 * is specified by the first element to print, and
 * ranges to the last element of the array.
 *
 * @param list contains the objects to print
 * @param first index of first element in 
 *     the <code>list</code> to print
 */
public void printRange(List<Printable> list, int first) {

Java syntax and its layout

Declarations

When declaring a variable or method make the accessibility as restrictive as possible. When using multiple keywords use the following ordering of keywords:

  1. accessibility - Start with the accessibility as it makes clear if the method or variable is reachable at all;
  2. static (if applicable);
  3. final (if applicable);
  4. return type (methods only) or type (for variables) - For readability, the type is as close to the name as possible.

This order is also compatible with the order that is used in Java for the main() method. This results in following sequence:

// A familiar one:
public static void main(String[] args) {}
private static String m_lastCreated = null;
private static final int RED = 4711;

Number per line

One declaration per line is recommended since it encourages commenting and it does not lead to confusing code. It also is more clear about the explicit initialization of variables as discussed in Initialization.

Example:

int level = 0; // level where user enters the system
int horizontalSize = 0; // horizontal size of current level layer

is preferred over:

int level, horizontalSize; // level and size of current level layer

Placement

In a method, declare local variables just before they are needed. This overcomes the problem of a big list of parameters at the beginning of a method and the use of a variable becomes more clearly in the context of the code, e.g. its initialization.

Initialization

The initialization of class variables is strictly not necessary because of the default initialization that takes place for these kinds of members. For some types, e.g. Booleans, this requires detailed knowledge of all the default values so it is more clear and explicit to initialize each member.

Variables that are used and declared within methods must always be initialized explicitly (the compiler will generate an error when you forget this).

Class and Interface Declarations

When coding Java classes and interfaces, the following formatting rules should be followed:

  • no space between a method and its parameter list;
  • { appears at the end of the same line as the declaration;
  • } starts a line by itself indented to match its corresponding opening statement, except when it is a null statement, in which the case the } should appear immediately after the {.

Example:

public class DefaultStrategy extends Strategy {
    private int m_attempts = 0;

    public DefaultStrategy(int attempts) {
                super();
        m_attempts = attempts;
    }

    void execute() {}
}

Statements

Each line should contain at most one statement.

Compound statements

Compound statements are statements that contain lists of statements enclosed in braces ("{...}"):

  • 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 Note that in the example the else if construction is started at a new line so the statement can not be overlooked.statements without accidentally introducing bugs due to forgetting to add braces.

if, if-else, if else-if else statements

There are a lot of nested possibilities for if-else constructions. All these variations can be programmed in very cryptic ways that easily and often will lead to buggy code. By being more explicit in the used coding style a lot of confusion can be taken away.

When using only one statement in a compound block brackets are optional. It is good practice, and therefore required, to always use brackets because mistakes can be made easily when adding a second statement and brackets are forgotten.

The following example illustrates the correct use of brackets in a few different if-then-else constructions:

if (condition) {
    statement1;
    statement2;
}
else {
    statement3;
}

if (condition) {
    statement1;
    statement2;
}
else if (condition1) {
    statement3;
    statement4;
}
else {
    statement5;
    statement6;
}

Note that in the example the else if construction is started at a new line so the statement can not be overlooked.

switch

When using a switch statement use following guidelines:

  • Consider including a default case, unless it would do nothing. The break in the default case is redundant, but it prevents a fall-through error if later another case is added;
  • The so-called fall-through construction should be avoided. Only when there are good reasons to use it, make sure that it is very clear that a fall-through is used (comment it).

The next example shows the sample code that uses the guidelines for a switch statement:

switch (condition) {
    case A:
        statements;
        // falls through here, because...
    case B:
        statements;
        break;
    default:
        statements;
        break;
}

try - catch

A try - catch statement should have the following format:

try {
    statements;
} 
catch (ExceptionClass e) {
    statements;
}

When using finally to add code that always will be executed this will look like:

try {
    statements;
} 
catch (ExceptionClass e) {
    statements;
}
finally {
    statements;
}

Note that the catch and the finally start at a new line in order to be compliant to the guidelines for if-then-else statements.

for loops

New style for loops are generally preferred over old style ones, unless you explicitly need the index, or you have to make the code run on pre-Java 5 virtual machines.

Old style, a good example that needs the index anyway:

// lookup a value in a list, return the index
List<Element> list;
for (int i = 0; i < list.size(); i++) {
    if (value.equals(list.get(i)) {
        return index;
    }
}

New style, a good example that iterates over a list without any need for an index or type casts:

// iterate over a list, printing all values
List<Element> list;
for (Element e : list) {
    System.out.println(" - " + e);
}

White Space

Blank lines

Blank lines improve readability by setting of sections of code that are logically related. One blank line should always be used in the following circumstances:

  • between class and interface definitions;
  • between methods;
  • before a block or single line comment;
  • between logical sections inside a method to improve readability.

Blank spaces

Blank spaces should be used in the following circumstances:

  • A keyword followed by a parenthesis should be separated by a space:
  • while (index > 5) {
        // ...
    }
    

    Note that blanks should not be used between a method call and its opening parenthesis. This helps to distinguish keywords from function calls;

  • Blanks should appear after commas in argument lists;
  • All binary and ternary operators except "." should be separated from their operands by spaces. Blanks should never separate unary operators such as unary minus, increment("++") and decrement("--") from their operands:
  • a += c + d;
    a = (a + b) / (c * d);
    a = (b > c) ? b : c;
    xCoord--;
    
  • The expressions in a for statement should be separated by blanks:
  • for (expr1; cond1; expr2) {
    }
    
  • Casts should be followed by a blank:
  • myInstance.doIt((TreeFrame) frame);
    

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.

(inner) classes, interfaces, enums and annotations

Names should be nouns, in mixed case with the first letter of each word capitalised. Try to keep your names simple and descriptive. Use whole words and avoid acronyms and abbreviations.

Examples:

class Raster
class TreeFrame

interfaces

Like class names, but if there is a name clash, the interface wins.

Example:

interface RemoteRepository extends Repository

services

Same as interfaces, so don't append "Service" as you usually do not know if an interface is a service or not.

Example:

interface ConnectionFactory

implementation classes

If a class implements an interface, it should use the name of the interface as part of its name, adding something specific for this implementation to it, or Impl if that does not make sense.

Examples:

class FileBasedRepository implements Repository
class VersionServlet implements HttpServlet

exceptions

Like class names; always ending in "Exception".

Example:

InputException

methods

Methods should be verbs in mixed case with the first letter lowercase. Within each method name capital letters separate words. Property methods or get-set methods are used as follows: When a method is used to get a value start the method name with 'get'. When a method is used to set a value start the method name with 'set'. When a method returns a boolean start the method name with 'is'.

Examples:

run();
runFast();
setBackground();
isOptional();

variables (except for (constant) static final variables and member variables)

All variables are in mixed case with a lowercase first letter. Words are separated by capital letters.

Examples:

int index;
float myWidth;

member variables

The same capitalisation as for normal variables prefixed with 'm_'.

Examples:

int m_index;
float m_myWidth;

constant (static final) variables, enum names

Names should be all uppercase with words separated by underscores ('_').

Example:

public static final int MAX_LIMIT = 99;

packages

Lowercase only; avoid lengthy package names; always start with org.apache.ace.

Example:

package org.apache.ace.demo.bundle;



Join our Question Answer community to learn and share your programming knowledge.

Solve these problems:

Java: How to convert a string to an integer in Java?

C#: Loops in c#

SQL: JOIN using more than 5 tables