#AskMe

Important Java Basic Code Conventions for Readable Code

Here I would like to give some basic code conventions in Java that mostly we need in our daily programming life:

Indentation

Use 4 spaces for indentation. No tabs!

If you are using Eclipse, you can configure this at

Brackets

Easy to read, place open braces on the line after the declaration, for example:

public class Foo extends Bar
{
    public static void main(String args[])
    {
        try
        {
            for (int i = 0; i < args.length; i++)
            {
                System.out.println(Integer.parseInt(args[i]));
            }
        }
        catch(NumberFormatException e)
        {
            e.printStackTrace();
        }
    }
}

Another popular one: Java convention (Eclipse) ~ I still like this one:

/**
 * Description here
 * @author ABC
 * @version $Revision$
 */
public class Foo extends Bar {
    public static void main(String args[]) {
        try {
            for (int i = 0; i < args.length; i++) {
                System.out.println(Integer.parseInt(args[i]));
            }
        } catch(NumberFormatException e) {
            e.printStackTrace();
        }
    }
}

Line Wrapping

Wrap lines longer than 100 characters. For wrapped lines, either use an indent of 8 characters or align with the expression at the same level on the previous line.

Declarations

Within a class or interface, definitions should be ordered as follows:

Imports

Do not use package imports (for example: import java.util.*;), please use full import for each class (for example: import java.util.LinkedList;)

For Eclipse Users

You can use built-in some formatter such as: Java Conventions [built-in] (my recommendation) that already apply well enough to code:

 

Some important shortcut keys: