Java Coding Conventions

Naveen AnamaneniUpdated · 7 min read

In a school notebook, everyone writes the date in the top corner, underlines headings and leaves a margin. Nobody is graded on it, yet a teacher can check thirty notebooks quickly because they all look the same. Code works the same way. A program spends much more time being read by people than being written, and code that follows the same layout everywhere is faster to read, review and fix. These shared layout rules are called coding conventions. In this lesson, you will learn the conventions most Java teams follow and see a messy class cleaned up step by step.

What Are Coding Conventions?

Coding conventions in Java are a set of agreed rules that are used to decide how code is laid out and written, not what it does. They cover indentation, braces, line length, the order of things in a file, imports, comments and modifiers. The compiler doesn't care about any of them; people do.

The two best-known guides are the original Oracle Code Conventions and the Google Java Style Guide. They agree on almost everything below. Many teams pick one, adjust a few details, and let a tool apply it automatically.

Naming (camelCase, PascalCase, UPPER_SNAKE_CASE) is a big part of conventions too. It is covered in "Java Naming Conventions", so this lesson focuses on everything else.

Layout and Formatting

RuleConvention
Indentation4 spaces per level (Google style uses 2). Never tabs mixed with spaces
Line lengthKeep lines under 100 characters (some teams use 120). Break long lines after a comma or before an operator
BracesOpening brace at the end of the line, closing brace on its own line
Always use bracesEven for a one-line if, for or while body
One statement per lineNo a++; b++; on the same line
One variable per declarationint total; and int count;, not int total, count;
SpacesAround operators (a + b), after commas and keywords (if (x)), not inside parentheses
Blank linesOne blank line between methods, and between logical steps inside a long method

The Order Inside a File

A Java source file follows the same top-to-bottom order everywhere:

  1. The package statement
  2. import statements (no blank lines between them in Google style, grouped in Oracle style)
  3. The class, with its members in this order:
    • static constants (static final)
    • other static fields
    • instance fields
    • constructors
    • methods, with related methods kept together (a public method followed by the private helpers it uses)
    • nested classes at the end

A Messy Class, Cleaned Up

Let's see a class that compiles and works, but breaks almost every convention.

FeeReport.java▶ Try it
import java.util.*;
public class FeeReport{
public static void main(String[] args){
List<String> n=new ArrayList<>(); int t=0,c=0;
n.add("Navika");n.add("Srihitha");n.add("Advitha");
int[] f={15000,14000,16000};
for(int i=0;i<f.length;i++) if(f[i]>14500) c++;
for(int x:f)t+=x;
System.out.println(n.size()+" students, total "+t+", above 14500: "+c);
}}
Output
3 students, total 45000, above 14500: 2

Now the same program with the conventions applied. The output is identical.

FeeReport.java▶ Try it
import java.util.List;
 
public class FeeReport {
 
    private static final int HIGH_FEE_LIMIT = 14_500;
 
    public static void main(String[] args) {
        List<String> students = List.of("Navika", "Srihitha", "Advitha");
        int[] fees = {15_000, 14_000, 16_000};
 
        int total = 0;
        int highFeeCount = 0;
        for (int fee : fees) {
            total += fee;
            if (fee > HIGH_FEE_LIMIT) {
                highFeeCount++;
            }
        }
 
        System.out.println(students.size() + " students, total " + total
                + ", above 14500: " + highFeeCount);
    }
}
Output
3 students, total 45000, above 14500: 2

Explanation:

  1. import java.util.* became a single import of what is used. Wildcard imports hide where a class comes from.
  2. Every block is indented by 4 spaces, and braces sit at the end of the opening line.
  3. int t=0,c=0; became two declarations with meaningful names, total and highFeeCount.
  4. The magic number 14500 became the constant HIGH_FEE_LIMIT, and long numbers use underscores (15_000) so they are easy to read.
  5. The if has braces, and the two loops became one clear loop.
  6. The long println line is broken before the + operator, with the continuation indented 8 spaces.

Imports

  • Import single classes, not whole packages with *.
  • Remove unused imports. Every IDE can do this for you.
  • Static imports (import static java.lang.Math.max;) are fine for constants and a few well-known helpers, but don't overuse them; a reader should still see where a method comes from.
  • Order: static imports first, then the rest, each sorted (most tools do this automatically).

Comments

DoDon't
Explain why the code does something unusualRepeat what the code already says (i++; // add 1 to i)
Write documentation comments on public classes and methodsLeave commented-out code; Git remembers old versions
Keep comments up to date when code changesWrite a long comment to excuse confusing code; rename and split it instead
Use // TODO: with a short reason for known gapsLeave TODOs for years

Modifiers, Literals and Annotations

RuleExample
Modifiers in the standard orderpublic static final, not final static public
Uppercase L for long literals10_000_000L, not 10_000_000l (a small l looks like 1)
Annotations on their own line for classes and methods@Override above the method
Always write @OverrideThe compiler then checks that you really override something
Array brackets with the typeString[] names, not String names[]

In Practice

  • Follow the project, not your habit. If an existing project uses 2-space indentation, use 2 spaces there. Consistency inside one codebase matters more than any single rule.
  • Agree once, automate forever. Teams keep a shared formatter configuration (an .editorconfig file, or an IDE code style file) in the repository.
  • Separate formatting from real changes. Reformatting a whole file in the same commit as a bug fix makes the fix hard to see in review.

Common Mistakes

Mixing tabs and spaces. The code looks fine in one editor and badly broken in another.

Wildcard imports. Two packages with a class of the same name (java.util.List and java.awt.List) cause confusing compile errors.

Comments that lie. A comment that was true three changes ago is worse than no comment.

Huge reformatting commits. They hide real changes and cause merge conflicts for everyone.

Practice

  1. Easy: Find three convention problems in this line and fix them: final static public int maxMarks=100;
  2. Harder: Take a program you wrote in an earlier lesson, run your IDE's Reformat Code and Optimize Imports actions, and list every change it made and which rule each one follows.

Quick check: Coding conventions

4 questions
1How many spaces is one indentation level in the Oracle conventions?
2Which modifier order is standard?
3Why should a one-line if still have braces?
4What should a good comment explain?

Key Takeaways

Was this tutorial helpful?

Lesson 536 of 578