Java Language


Oracle Official Code Standard All Versions

Java SE 1.0
Java SE 1.1
Java SE 1.2
Java SE 1.3
Java SE 1.4
Java SE 5
Java SE 6
Java SE 7
Java SE 8
Java SE 9 (Early Access)

This draft deletes the entire topic.

Introduction

Oracle official code standard for the Java Programming Language is a standard followed by developers at Sun and recommended to be followed by any other java developer. It covers filenames, file organization, indentation, comments, declarations, statements, white space, naming conventions, programming practices and includes a code example.

expand all collapse all

Examples

  • 25

    Package names

    • Package names should be all lower case without underscores or other special characters.
    • Package names begin with the reversed authority part of the web address of the company of the developer. This part can be followed a by project/program structure dependent package substructure.
    • Don’t use plural form. Follow the convention of the standard API which uses for instance java.lang.annotation and not java.lang.annotations.
    • Examples: com.yourcompany.widget.button, com.yourcompany.core.api

    Class, Interface and Enum Names

    • Class and enum names should typically be nouns.
    • Interface names should typically be nouns or adjectives ending with …able.
    • Use mixed case with the first letter in each word in upper case (i.e. CamelCase).
    • Match the regular expression ^[A-Z][a-zA-Z0-9]*$.
    • Use whole words and avoid using abbreviations unless the abbreviation is more widely used than the long form.
    • Format an abbreviation as a word if the it is part of a longer class name.
    • Examples: ArrayList, BigInteger, ArrayIndexOutOfBoundsException, Iterable.

    Method Names

    Method names should typically be verbs or other descriptions of actions

    • They should match the regular expression ^[a-z][a-zA-Z0-9]*$.
    • Use mixed case with the first letter in lower case.
    • Examples: toString, hashCode

    Variables

    Variable names should be in mixed case with the first letter in lower case

    • Match the regular expression ^[a-z][a-zA-Z0-9]*$
    • Further recommendation: Variables
    • Examples: elements, currentIndex

    Type Variables

    For simple cases where there are few type variables involved use a single upper case letter.

    • Match the regular expression ^[A-Z][0-9]?$
    • If one letter is more descriptive than another (such as K and V for keys and values in maps or R for a function return type) use that, otherwise use T.
    • For complex cases where single letter type variables become confusing, use longer names written in all capital letters and use underscore (_) to separate words.
    • Examples: T, V, SRC_VERTEX

    Constants

    Constants (static final fields whose content is immutable, by language rules or by convention) should be named with all capital letters and underscore (_) to separate words.

    • Match the regular expression ^[A-Z][A-Z0-9]*(_[A-Z0-9]+)*$
    • Examples: BUFFER_SIZE, MAX_LEVEL

    Other guidelines on naming

    • Avoid hiding/shadowing methods, variables and type variables in outer scopes.
    • Let the verbosity of the name correlate to the size of the scope. (For instance, use descriptive names for fields of large classes and brief names for local short-lived variables.)
    • When naming public static members, let the identifier be self descriptive if you believe they will be statically imported.
    • Further reading: Naming Section (in the official Java Style Guide)

    Source: Java Style Guidelines from Oracle

  • 12

    Order of class members

    Class members should be ordered as follows:

    1. Fields (in order of public, protected and private)
    2. Constructors
    3. Factory methods
    4. Other Methods (in order of public, protected and private)

    Ordering fields and methods primarily by their access modifiers or identifier is not required.

    Here is an example of this order:

    class Example {
    
        private int i;
    
        Example(int i) {
            this.i = i;
        }
    
        static Example getExample(int i) {
            return new Example(i);
        }
    
        @Override
        public String toString() {
            return "An example [" + i + "]";
        }
    
    }
    

    Grouping of class members

    • Related fields should be grouped together.
    • A nested type may be declared right before its first use; otherwise it should be declared before the fields.
    • Constructors and overloaded methods should be grouped together by functionality and ordered with increasing arity. This implies that delegation among these constructs flow downward in the code.
    • Constructors should be grouped together without other members between.
    • Overloaded variants of a method should be grouped together without other members between.
  • 7

    Declaration annotations should be put on a separate line from the declaration being annotated.

    @SuppressWarnings("unchecked")
    public T[] toArray(T[] typeHolder) {
        ...
    }
    

    However, few or short annotations annotating a single-line method may be put on the same line as the method if it improves readability. For example, one may write:

    @Nullable String getName() { return name; }
    

    For a matter of consistency and readability, either all annotations should be put on the same line or each annotation should be put on a separate line.

    // Bad.
    @Deprecated @SafeVarargs
    @CustomAnnotation
    public final Tuple<T> extend(T... elements) {
        ...
    }
    
    // Even worse.
    @Deprecated @SafeVarargs
    @CustomAnnotation public final Tuple<T> extend(T... elements) {
        ...
    }
    
    // Good.
    @Deprecated
    @SafeVarargs
    @CustomAnnotation
    public final Tuple<T> extend(T... elements) {
        ...
    }
    
    // Good.
    @Deprecated @SafeVarargs @CustomAnnotation
    public final Tuple<T> extend(T... elements) {
        ...
    }
    
Please consider making a request to improve this example.

Syntax

Syntax

Parameters

Parameters

Remarks

  • The examples above strictly follow the new official style guide from Oracle. They are in other words not subjectively made up by the authors of this page.

  • The official style guide has been carefully written to be backward compatible with the original style guide and the majority of code out in the wild.

  • The official style guide has been peer reviewed by among others, Brian Goetz (Java Language Architect) and Mark Reinhold (Chief Architect of the Java Platform).

  • The examples are non-normative; While they intend to illustrate correct way of formatting the code, there may be other ways to correctly format the code. This is a general principle: There may be several ways to format the code, all adhering to the official guidelines.

Still have a question about Oracle Official Code Standard? Ask Question

Topic Outline