Coding Guidelines in Java
Last Updated :
24 Jan, 2022
Java is one of the most popular and widely used programming languages and platforms. A platform is an environment that helps to develop and run programs written in any programming language. Java is fast, reliable, and secure. From desktop to web applications, scientific supercomputers to gaming consoles, cell phones to the Internet, Java is used in every nook and corner.
In this article, let us understand a few coding guidelines that help to increase the readability of the program.
Why Coding Guidelines?
The coding guidelines are important because most of the software cost goes towards maintenance. And also, the software is not always developed by a single developer. Therefore, maintaining a convention for writing software increases the readability of the program.
A few of the guidelines are:
1. Naming Conventions: We generally follow the camel case convention in java programming. It means that all the classes and interfaces should be nouns, in mixed cases with the first letter of each internal word capitalized. All the methods should be verbs, in mixed case with the first letter lowercase and with the first letter of each internal word capitalized. The variables should be meaningful and one character variable names must be avoided. A constant variable is defined in the capital case.
2. Curly Braces: Curly braces are used to define the bodies of classes, methods, and loops. There are two standard formats for the usage of curly braces, either of which is used.
- No blank lines should be present after the opening brace or before the closing brace.
- A curly brace is applied at the end of the line that starts the class, method, loop, etc., and the closing brace is on a line by itself, lined up vertically with the start of the first line. For example:
class Geeksforgeeks {
... Geeksforgeeks(){
// Constructor
...
}
int Geek(int a, float b){
... for (int i = 0; i < Field; i++){
....
}
}
}
- Each curly brace is added on a new line, and the pair is aligned vertically. The preceding code snippet in this format would be as follows:
class Geeksforgeeks
{
... Geeksforgeeks()
{ // Constructor
...
}
int Geek(int a, float b)
{
... for (int i = 0; i < Field; i++)
{
....
}...;
}
}
3. Indentation: The unit of indentation should be 4 spaces. Tab-stops should be set exactly every 8 spaces. All indentation must be achieved by the space character and tab characters must not exist in the resultant source file. The recognized standard for increasing readability of each line is:
- Apply indentation to alike items in a vertical list (such as end-of-line comments, and identifiers in declarations).
- Surround the binary operators (including assignment) by spaces.
- Follow a semicolon or comma by a space.
- Add a space between a keyword("if", "while", "return", "catch", "switch", "for") and a succeeding parenthesis.
- Surplus parentheses can also help to highlight the structure of expressions (but avoid using too many nested parentheses).
- Insert blank lines to differentiate between the important parts of the code.
- Let's implement all the above guidelines in a code:
class Geeksforgeeks {
private int s;
private double d;
Geeksforgeeks()
{ // Constructor
s = 1;
d = 3.14;
}
int Geek(int a, float b)
{
// Must initialize local variables
int l = 0;
float le = 1;
int n = 10;
l = n - 2;
le = l + b * 3;
for (int i = 0; i & lt; n; i++) {
l = l * 2;
l = l - n;
}
return l + a;
}
}
4. White Space: White spaces also play a major part in readability as follows:
- Operators should be surrounded by a space character. For example:
The operation should be written as:
a = (b + c) * d;
And not as:
a=(b+c)*d
The loop must be initialized as:
while (true) {...}
And not as:
while(true){...}
- Commas should be followed by white space. For example:
The functions must be initialized as:
fun(a, b, c, d);
And not as:
fun(a, b, c, d);
- Colons should be surrounded by white space. For example:
The case statements must be initialized as:
case 100 : break;
And not as:
case 100:break;
- Semicolons in for statements should be followed by a space character. For example:
The for loop must be initialized as:
for (i = 0; i < n; i++)
And not as:
for(i=0;i<n;i++)
5. Comments: Java programs can have two types of comments. They are Implementation and Documentation. Comments should contain only the information that is relevant for reading and understanding the program. For example, information about how the package is built or in what directory it resides should not be included in the program as a comment.
- Implementation Comments: Implementation comments are delimited by //. Java also allows the use of /*...*/ for implementation comments. Implementation comments are used for notes about a particular implementation or for temporarily removing code. Programs can have four styles of implementation comments: block, single-line, trailing, and temporarily removing code.
- Block comments are used to provide descriptions of files, methods, data structures, and algorithms. Block comments may be used at the beginning of each file and before each method or within methods. Block comments inside a method should be indented to the same level as the code they describe. A block comment should have a blank line before its start unless it comes immediately after the start of a compound statement. For example:
// block comment on line 1
// block comment on line 2
// block comment on line 3
- Single-line comments can appear on a single line indented to the level of the code that follows. If a comment can not be written in a single line, it should follow the block comment format. A single-line comment should be preceded by a blank line unless it comes immediately after the start of a compound statement. For example:
a = 10;
b = 20;
// a single-line comment
c = a * b;
- Trailing(very short) comments can appear on the same line of the code they describe but should be separated from the code at a far off distance. If more than one short comment appears in a section of related code, they should all be indented to the same tab setting. For example:
if (a == 2) {
b = true; // special case
}
else {
c = isPrime(x); // works only for odd
}
- Temporarily removing code: The // delimiter can comment out a partial or a complete line. It can also be used in multiple lines to comment out entire sections of code. It is important to note that this should only be used temporarily while the code is in active development; the unused code should eventually be physically removed as it can make the source more difficult to maintain. For example:
if (a > 1) {
b = a; // + 1;
...
}
else {
// b = 2;
...
}
- Documentation Comments: Documentation comments describe Java classes, interfaces, constructors, methods, and fields. They are delimited by /**…*/. Note the double-asterisk (**) at the beginning with one comment per class, interface, or member. This comment should appear just before the declaration with no space between the comment and the code it refers to. Documentation comments can be extracted to HTML files using the javadoc tool. Javadoc of class members can be specified on a single line as follows:
/** This is a java documentation comment */
private int comments_;
Documentation comments are meant to describe the specification of the code, from an implementation-free perspective, to be read by developers who might not necessarily have the source code at hand. Java associates documentation comments with the first declaration after the comment. As a result, documentation comments should not be present inside a method or constructor definition block. For example:
Though we can say that the above-mentioned guidelines are not definitive and they are relative, but it is always preferred to maintain the guidelines because the software is never developed by a single person and might not be maintained by the same team who has developed the software. In order to solve any bugs in the software, the deployed code must be easily readable. Following the above guidelines makes the code readable not only for the developer but also for a new person who is reading the code for the first time.
Similar Reads
File Handling in Java
In Java, with the help of File Class, we can work with files. This File Class is inside the java.io package. The File class can be used to create an object of the class and then specifying the name of the file.Why File Handling is Required?File Handling is an integral part of any programming languag
6 min read
Naming Conventions in Java
A programmer is always said to write clean codes, where naming has to be appropriate so that for any other programmer it acts as an easy way out to read the code. At a smaller level, this seems meaningless but think of the industrial level where it becomes necessary to write clean codes in order to
5 min read
Inheritance in Java
Java Inheritance is a fundamental concept in OOP(Object-Oriented Programming). It is the mechanism in Java by which one class is allowed to inherit the features(fields and methods) of another class. In Java, Inheritance means creating new classes based on existing ones. A class that inherits from an
13 min read
Closures in Java with Examples
A method is a collection of statements that perform some specific task and return the result to the caller. A method can perform some specific task without returning anything. Methods allow us to reuse the code without retyping the code. In Java, every method must be part of some class that is diffe
5 min read
Java Exception Handling
Exception handling in Java allows developers to manage runtime errors effectively by using mechanisms like try-catch block, finally block, throwing Exceptions, Custom Exception handling, etc.An Exception is an unwanted or unexpected event that occurs during the execution of a program (i.e., at runti
10 min read
Java Identifiers
An identifier in Java is the name given to Variables, Classes, Methods, Packages, Interfaces, etc. These are the unique names used to identify programming elements. Every Java Variable must be identified with a unique name.Example:public class Test{ public static void main(String[] args) { int a = 2
2 min read
CharsetDecoder Class in Java
For encoding and decoding tasks, many methods are offered in Charset Encoder and Charset Decoder classes in Java. The Charset Decoder class is used for text handling to convert bytes to characters. The Charset decoder accepts a sequence of bytes as its input and displays Unicode characters as output
5 min read
Java Fundamentals Coding Practice Problems
Understanding Java fundamentals is the first step to becoming a proficient Java programmer. This collection of Java basic coding practice problems covers essential topics such as input/output operations, arithmetic and logical operators, type conversion, conditional statements, loops, and more. Thes
1 min read
10 Best Java Compilers in 2025
Java Compilers refers to a program that takes the text file work of a software developer and compiles it into a platform-independent Java file. The Java compilers mainly include the Java Programming language compilers (javac), the Eclipse compiler for Java(ECJ), the GNU, and Jikes. The Java Compiler
7 min read
Classes and Objects in Java
In Java, classes and objects are basic concepts of Object Oriented Programming (OOPs) that are used to represent real-world concepts and entities. The class represents a group of objects having similar properties and behavior, or in other words, we can say that a class is a blueprint for objects, wh
11 min read