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.
java.lang.annotation
and not java.lang.annotations
.com.yourcompany.widget.button
, com.yourcompany.core.api
^[A-Z][a-zA-Z0-9]*$
.ArrayList
, BigInteger
, ArrayIndexOutOfBoundsException
, Iterable
.Method names should typically be verbs or other descriptions of actions
^[a-z][a-zA-Z0-9]*$
.toString
, hashCode
Variable names should be in mixed case with the first letter in lower case
^[a-z][a-zA-Z0-9]*$
elements
, currentIndex
For simple cases where there are few type variables involved use a single upper case letter.
^[A-Z][0-9]?$
K
and V
for keys and values in maps or R
for a function return type) use that, otherwise use T
._
) to separate words.T
, V
, SRC_VERTEX
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.
^[A-Z][A-Z0-9]*(_[A-Z0-9]+)*$
BUFFER_SIZE
, MAX_LEVEL
Source: Java Style Guidelines from Oracle
All lines must be terminated with a line feed character (LF, ASCII value 10) and not for instance CR or CR+LF.
There may be no trailing white space at the end of a line.
The name of a source file must equal the name of the class it contains followed by the .java
extension, even for files that only contain a package private class. This does not apply to files that do not contain any class declarations, such as package-info.java
.
Apart from LF the only allowed white space character is Space (ASCII value 32). Note that this implies that other white space characters (in, for instance, string and character literals) must be written in escaped form.
\'
, \"
, \\
, \t
, \b
, \r
, \f
, and \n
should be preferred over corresponding octal (e.g. \047
) or Unicode (e.g. \u0027
) escaped characters.
Should there be a need to go against the above rules for the sake of testing, the test should generate the required input programatically.
package com.example.my.package;
The package declaration should not be line wrapped, regardless of whether it exceeds the recommended maximum length of a line.
// First java/javax packages
import java.util.ArrayList;
import javax.tools.JavaCompiler;
// Then third party libraries
import com.fasterxml.jackson.annotation.JsonProperty;
// Then project imports
import com.example.my.package.ClassA;
import com.example.my.package.ClassB;
// Then static imports (in the same order as above)
import static java.util.stream.Collectors.toList;
Import statements should be sorted…
Import statements should not be line wrapped, regardless of whether it exceeds the recommended maximum length of a line.
No unused imports should be present.
Class members should be ordered as follows:
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 + "]";
}
}
class ExampleClass {
// Access modifiers first (don't do for instance "static public")
public static void main(String[] args) {
System.out.println("Hello World");
}
}
interface ExampleInterface {
// Avoid 'public' and 'abstract' since they are implicit
void sayHello();
}
Modifiers should go in the following order
public
/ private
/ protected
)abstract
static
final
transient
volatile
default
synchronized
native
strictfp
Modifiers should not be written out when they are implicit. For example, interface methods should neither be declared public
nor abstract
, and nested enums and interfaces should not be declared static.
Method parameters and local variables should not be declared final
unless it improves readability or documents an actual design decision.
Fields should be declared final
unless there is a compelling reason to make them mutable.
case
lines should be indented with four spaces, and statements within the case should be indented with another four spaces.switch (var) {
case TWO:
setChoice("two");
break;
case THREE:
setChoice("three");
break;
default:
throw new IllegalArgumentException();
}
Refer to Wrapping statements for guidelines on how to indent continuation lines.
Source code and comments should generally not exceed 80 characters per line and rarely if ever exceed 100 characters per line, including indentation.
The character limit must be judged on a case by case basis. What really matters is the semantical “density” and readability of the line. Making lines gratuitously long makes them hard to read; similarly, making “heroic attempts” to fit them into 80 columns can also make them hard to read. The flexibility outlined here aims to enable developers to avoid these extremes, not to maximize use of monitor real-estate.
URLs or example commands should not be wrapped.
// Ok even though it might exceed max line width when indented.
Error e = isTypeParam
? Errors.InvalidRepeatableAnnotationNotApplicable(targetContainerType, on)
: Errors.InvalidRepeatableAnnotationNotApplicableInContext(targetContainerType));
// Wrapping preferable
String pretty = Stream.of(args)
.map(Argument::prettyPrint)
.collectors(joining(", "));
// Too strict interpretation of max line width. Readability suffers.
Error e = isTypeParam
? Errors.InvalidRepeatableAnnotationNotApplicable(
targetContainerType, on)
: Errors.InvalidRepeatableAnnotationNotApplicableInContext(
targetContainerType);
// Should be wrapped even though it fits within the character limit
String pretty = Stream.of(args).map(Argument::prettyPrint).collectors(joining(", "));
Wrapping at a higher syntactical level is preferred over wrapping at a lower syntactical level.
There should be at most 1 statement per line.
A continuation line should be indented in one of the following four ways
int someMethod(String aString,
List<Integer> aList,
Map<String, String> aMap,
int anInt,
long aLong,
Set<Number> aSet,
double aDouble) {
…
}
int someMethod(String aString, List<Integer> aList,
Map<String, String> aMap, int anInt, long aLong,
double aDouble, long aLong) {
…
}
int someMethod(String aString,
List<Map<Integer, StringBuffer>> aListOfMaps,
Map<String, String> aMap)
throws IllegalArgumentException {
…
}
int someMethod(String aString, List<Integer> aList,
Map<String, String> aMap, int anInt)
throws IllegalArgumentException {
…
}
popupMsg("Inbox notification: You have "
+ newMsgs + " new messages");
// Don't! Looks like two arguments
popupMsg("Inbox notification: You have " +
newMsgs + " new messages");
A single blank line should be used to separate…
…and may be used to separate logical groups of
Multiple consecutive blank lines should only be used to separate groups of related members and not as the standard inter-member spacing.
A single space should be used…
//
that starts a comment.In variable declarations it is not recommended to align types and variables.
String[] args
) and not on the variable (String args[]
).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) {
...
}
Runnable r = () -> System.out.println("Hello World");
Supplier<String> c = () -> "Hello World";
// Collection::contains is a simple unary method and its behavior is
// clear from the context. A method reference is preferred here.
appendFilter(goodStrings::contains);
// A lambda expression is easier to understand than just tempMap::put in this case
trackTemperature((time, temp) -> tempMap.put(time, temp));
return flag ? "yes" : "no";
String cmp = (flag1 != flag2) ? "not equal" : "equal";
// Don't do this
return (flag ? "yes" : "no");
return
keyword must not be surrounded by parentheses.long l = 5432L;
int i = 0x123 + 0xABC;
byte b = 0b1010;
float f1 = 1 / 5432f;
float f2 = 0.123e4f;
double d1 = 1 / 5432d; // or 1 / 5432.0
double d2 = 0x1.3p2;
long
literals should use the upper case letter L
suffix.A
-F
.class Example {
void method(boolean error) {
if (error) {
Log.error("Error occurred!");
System.out.println("Error!");
} else { // Use braces since the other block uses braces.
System.out.println("No error");
}
}
}
Opening braces should be put on the end of the current line rather than on a line by its own.
There should be a new line in front of a closing brace unless the block is empty (see Short Forms below)
Braces are recommended even where the language makes them optional, such as single-line if and loop bodies.
if
/ else
statement has braces, the other block must too.The else
, catch
and the while
keyword in do…while
loops go on the same line as the closing brace of the preceding block.
enum Response { YES, NO, MAYBE }
public boolean isReference() { return true; }
The above recommendations are intended to improve uniformity (and thus increase familiarity / readability). In some cases “short forms” that deviate from the above guidelines are just as readable and may be used instead. These cases include for instance simple enum declarations and trivial methods and lambda expressions.