Java Coding Conventions
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
| Rule | Convention |
|---|---|
| Indentation | 4 spaces per level (Google style uses 2). Never tabs mixed with spaces |
| Line length | Keep lines under 100 characters (some teams use 120). Break long lines after a comma or before an operator |
| Braces | Opening brace at the end of the line, closing brace on its own line |
| Always use braces | Even for a one-line if, for or while body |
| One statement per line | No a++; b++; on the same line |
| One variable per declaration | int total; and int count;, not int total, count; |
| Spaces | Around operators (a + b), after commas and keywords (if (x)), not inside parentheses |
| Blank lines | One 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:
- The
packagestatement importstatements (no blank lines between them in Google style, grouped in Oracle style)- 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
- static constants (
A Messy Class, Cleaned Up
Let's see a class that compiles and works, but breaks almost every convention.
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);
}}3 students, total 45000, above 14500: 2Now the same program with the conventions applied. The output is identical.
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);
}
}3 students, total 45000, above 14500: 2Explanation:
import java.util.*became a single import of what is used. Wildcard imports hide where a class comes from.- Every block is indented by 4 spaces, and braces sit at the end of the opening line.
int t=0,c=0;became two declarations with meaningful names,totalandhighFeeCount.- The magic number 14500 became the constant
HIGH_FEE_LIMIT, and long numbers use underscores (15_000) so they are easy to read. - The
ifhas braces, and the two loops became one clear loop. - The long
printlnline 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
| Do | Don't |
|---|---|
| Explain why the code does something unusual | Repeat what the code already says (i++; // add 1 to i) |
| Write documentation comments on public classes and methods | Leave commented-out code; Git remembers old versions |
| Keep comments up to date when code changes | Write a long comment to excuse confusing code; rename and split it instead |
Use // TODO: with a short reason for known gaps | Leave TODOs for years |
Modifiers, Literals and Annotations
| Rule | Example |
|---|---|
| Modifiers in the standard order | public static final, not final static public |
Uppercase L for long literals | 10_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 @Override | The compiler then checks that you really override something |
| Array brackets with the type | String[] 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
.editorconfigfile, 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
- Easy: Find three convention problems in this line and fix them:
final static public int maxMarks=100; - 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.
Key Takeaways
Was this tutorial helpful?