Java Coding Standard
Java Coding Standard
Naming
Layout
Statements: Package/Import | Classes and Interfaces | Methods | Types | Variables | Loops | Conditionals
Comments
References
Contributors
Naming
Names representing packages should be in all lower case.
com.company.application.ui
Constant names must be all uppercase using underscore to separate words (aka SCREAMING_SNAKE_CASE). To find what exactly are considered constants, refer to this page in the
Google Java Style Guide.
MAX_ITERATIONS, COLOR_RED
Underscores may be used in test method names using the following three part format featureUnderTest_testScenario_expectedBehavior()
e.g. sortList_emptyList_exceptionThrown() getMember_memberNotFound_nullReturned
Third part or both second and third parts can be omitted depending on what's covered in the test. For example, the test method sortList_emptyList() will test sortList() method for all
variations of the 'empty list' scenario and the test method sortList() will test the sortList() method for all scenarios.
Abbreviations and acronyms should not be uppercase when used as a part of a name.
Good Bad
exportHtmlSource(); exportHTMLSource();
openDvdPlayer(); openDVDPlayer();
// methods
boolean hasLicense();
boolean canEvaluate();
boolean shouldAbort = false;
As much as possible, use a prefix such as is , has , was , etc. for boolean variable/method names so that linters can automatically verify that this style rule is being followed.
Rationale: This is the naming convention for boolean methods and variables used by Java core packages. It also makes the code read like normal English e.g. if(isOpen) ...
Rationale: Enhances readability since the name gives the user an immediate clue of the type of the variable and the operations that can be performed on its elements. One space character
after the variable type is enough to obtain clarity.
Iterator variables can be called i, j, k etc.
Variables named j, k etc. should be used for nested loops only.
for (Iterator i = points.iterator(); i.hasNext(); ) {
...
}
Rationale: The notation is taken from mathematics where it is an established convention for indicating iterators.
Associated constants should have a common prefix.
static final int COLOR_RED = 1;
static final int COLOR_GREEN = 2;
static final int COLOR_BLUE = 3;
Rationale: This indicates that they belong together, and make them appear together when sorted alphabetically.
Layout
Basic indentation should be 4 spaces (not tabs).
for (i = 0; i < nElements; i++) {
a[i] = 0;
}
https://se-education.org/guides/conventions/java/index.html 2/9
17/03/2025, 14:31 Java coding standard
Try to keep line length shorter than 110 characters (soft limit). But it is OK to exceed the limit slightly (hard limit: 120 chars). If the line exceeds the limit, use line wrapping at appropriate places
of the line.
Indentation for wrapped lines should be 8 spaces (i.e. twice the normal indentation of 4 spaces) more than the parent line.
setText("Long line split"
+ "into two parts.");
if (isReady) {
setText("Long line split"
+ "into two parts.");
}
A method or constructor name stays attached to the open parenthesis ( that follows it.
Good someMethodWithVeryVeryVeryVeryVeryVeryVeryVeryVeryVeryVeryLongName(
int anArg, Object anotherArg);
Bad someMethodWithVeryVeryVeryVeryVeryVeryVeryVeryVeryVeryVeryLongName
(int anArg, Object anotherArg);
Prefer higher-level breaks to lower-level breaks. In the example below, the first is preferred, since the break occurs outside the parenthesized expression, which is at a higher level.
Good longName1 = longName2 * (longName3 + longName4 - longName5)
+ 4 * longname6
The while and the do-while statements should have the following form:
while (condition) { do {
statements; statements;
} } while (condition);
The switch statement should have the following form: Note there is no indentation for case clauses.
Configure your IDE to follow this style instead.
switch (condition) {
case ABC:
statements;
// Fallthrough
case DEF:
statements;
break;
case XYZ:
statements;
break;
default:
statements;
break;
}
Lambda-style switch statements/expressions can have indented case blocks (as shown below):
switch (condition) {
case ABC -> method("1");
case DEF -> method("2");
case XYZ -> method("3");
default -> method("0");
}
The explicit // Fallthrough comment should be included whenever there is a case statement without a break statement.
Rationale: Leaving out the break is a common error, and it must be made clear that it is intentional when it is not there.
A try-catch statement should have the following form:
try { try {
statements; statements;
} catch (Exception exception) { } catch (Exception exception) {
statements; statements;
} } finally {
statements;
}
https://se-education.org/guides/conventions/java/index.html 4/9
17/03/2025, 14:31 Java coding standard
Rule Good Bad
Java reserved words should be followed by a white space. while (true) { while(true){
Colons should be surrounded by white space when for (i = 0; i < 10; i++) { for(i=0;i<10;i++){
used as a binary/ternary operator.
Does not apply to switch x: . Semicolons in for
statements should be followed by a space character.
Rationale: Makes the individual components of the statements stand out and enhances readability.
Logical units within a block should be separated by one blank line.
// Create a new identity matrix
Matrix4x4 matrix = new Matrix4x4();
// Apply rotation
transformation.multiply(matrix);
Rationale: Enhances readability by introducing white space between logical units. Each block is often introduced by a comment as indicated in the example above.
Statements
Example:
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import java.io.File;
import java.io.IOException;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import org.loadui.testfx.GuiTest;
import org.testfx.api.FxToolkit;
import com.google.common.io.Files;
import javafx.geometry.Bounds;
import javafx.geometry.Point2D;
import junit.framework.AssertionFailedError;
IDEs have support for auto-ordering import statements. However, note that the default orderings of different IDEs are not always the same. It is recommended that you and your team use
the same IDE and stick to a consistent ordering.
https://se-education.org/guides/conventions/java/index.html 5/9
17/03/2025, 14:31 Java coding standard
Imported classes should always be listed explicitly.
Good Bad
import java.util.List; import java.util.*;
import java.util.ArrayList;
import java.util.HashSet;
Rationale: Importing classes explicitly gives an excellent documentation value for the class at hand and makes the class easier to comprehend and maintain. Appropriate tools should be
used in order to always keep the import list minimal and up to date. IDE's can be configured to do this easily.
Methods
Method modifiers should be given in the following order:
<access> static abstract synchronized <unusual> final native
Rationale: The most important point here is to keep the access modifier as the first modifier. The order is less important for the other modifiers , but it make sense to have a fixed convention.
Types
Array specifiers must be attached to the type not the variable.
Good Bad
int[] a = new int[20]; int a[] = new int[20];
Rationale: The arrayness is a feature of the base type, not the variable. Java allows both forms however.
Variables
Variables should be initialized where they are declared and they should be declared in the smallest scope possible.
Good Bad
int sum = 0; int i, j, sum;
for (int i = 0; i < 10; i++) { sum = 0;
for (int j = 0; j < 10; j++) { for (i = 0; i < 10; i++) {
sum += i * j; for (j = 0; j < 10; j++) {
} sum += i * j;
} }
}
https://se-education.org/guides/conventions/java/index.html 6/9
17/03/2025, 14:31 Java coding standard
Rationale: This ensures that variables are valid at any time. Sometimes it is impossible to initialize a variable to a valid value where it is declared. In these cases it should be left uninitialized
rather than initialized to some phony value.
Class variables should never be declared public unless the class is a data class with no behavior. This rule does not apply to constants.
Bad
public class Foo{
Rationale: The concept of Java information hiding and encapsulation is violated by public variables. Use non-public variables and access functions instead.
Avoid unnecessary use of this with fields.
Use the this keyword only when a field is shadowed by a method or constructor parameter.
Good Bad
public User(String name) { public User(String name) {
this.name = name; // 'id' is not shadowed by any method parameters
... this.id = User.getNewId();
} ...
}
Loops
The loop body should be wrapped by curly brackets irrespective of how many lines there are in the body.
Good Bad
for (i = 0; i < 100; i++) { for (i = 0, sum = 0; i < 100; i++)
sum += value[i]; sum += value[i];
}
Rationale: When there is only one statement in the loop body, Java allows it to be written without wrapping it between { } . However that is error prone and very strongly discouraged from
using.
Conditionals
The conditional should be put on a separate line.
Good Bad
if (isDone) { if (isDone) doCleanup();
doCleanup();
}
Rationale: This helps when debugging using an IDE debugger. When writing on a single line, it is not apparent whether the condition is really true or not.
Single statement conditionals should still be wrapped by curly brackets.
Good Bad
InputStream stream = File.open(fileName, "w"); InputStream stream = File.open(fileName, "w");
if (stream != null) { if (stream != null)
readFile(stream); readFile(stream);
}
The body of the conditional should be wrapped by curly brackets irrespective of how many statements.
Rationale: Omitting braces can lead to subtle bugs.
Comments
https://se-education.org/guides/conventions/java/index.html 7/9
17/03/2025, 14:31 Java coding standard
All comments should be written in English.
Furthermore, use American spelling and avoid local slang.
Rationale: The code is meant for an international audience.
Note in particular:
The opening /** on a separate line.
Write the first sentence as a short summary of the method, as Javadoc automatically places it in the method summary table (and index).
In method header comments, the first sentence should start in the form Returns ... , Sends ... , Adds ... etc. (not Return or Returning etc.)
Subsequent * is aligned with the first one.
Space after each * .
Empty line between description and parameter section.
Punctuation behind each parameter description.
No blank line between the documentation block and the method/class.
@return can be omitted if the method does not return anything or the return value is obvious from the rest of the comment.
@param s can be omitted if all parameters of a method have self-explanatory names, or they are already explained in the main part of the comment i.e., if none of the @param s add any
value. This means the comment will have @param for all its parameters, or none.
When writing Javadocs for overridden methods, the @inheritDoc tag can be used to reuse the header comment from the parent method but with further modifications e.g., when the
method has a slightly different behavior from the parent method.
Javadoc of class members can be specified on a single line as follows:
/** Number of connections to this database */
private int connectionCount;
Rationale: This is to avoid the comments from breaking the logical structure of the program.
Note that trailing comments such as the below are allowed as well.
process('ABC'); // process a dummy String frst
https://se-education.org/guides/conventions/java/index.html 8/9
17/03/2025, 14:31 Java coding standard
References
1. Oracle's Java Style Guide https://www.oracle.com/docs/tech/java/codeconventions.pdf
2. Google's Java Style Guide https://google.github.io/styleguide/javaguide.html
Contributors
Nimantha Baranasuriya - Initial draft
Dai Thanh - Further tweaks
Tong Chun Kit - Further tweaks
Barnabas Tan - Converted from Google Docs to Markdown Document
https://se-education.org/guides/conventions/java/index.html 9/9