Best Coding Practices for Java

By using best practices, common language expressions, and good programming styles we can produce reliable software that is well written and easy to maintain. Today more than ever, teams are building enterprise Java applications that are reliable, scalable and maintainable. In order to work as efficiently as possible, teams must adopt proven design standards and good coding standards. Using this post as a guideline to writing quality Java code will start you and your organization on your way.

Begin with a set of Guidelines

Let’s start with the following:

  • Readability – Make the programs as readable as possible by enforcing proper spacing, tabs, indentations, naming conventions, etc.
  • Simplicity – Let your guiding principle coined by the U.S. Navy in the 1960’s (KISS) – Keep it Simple, Stupid or Keep is Stupid Simple. Simplicity should be the key goal in the design and unnecessary complexity should be avoided.
  • Convention – Make use of standard conventions and good practices as much as possible. Variables and functions are camel-case, classes are cap-cased, and constants are all-caps.
public void functionName
public class ClassName {…}

Source Code Guidelines


  • Doc Comments — Source files (*.java) should begin with c-style documentation comments containing the Title, Version, Date mm/dd/yyyy format and copyright information. Best practices dictates that we document our source code as much as possible.
* Copyright (c) 2005, 2006,   All rights reserved.
* This module defines the Customer model and all of its
* data elements.  
* @author Amaury Valdes
* @version 1.0
* @since 09/25/2005
  • Line Comments — If you need to comment a single line of code you can use the double-slash // notation. This will ignore everything to the right of the double-slash.

// Print Sample Message Below
System.out.println("Sample Message !!!");

  • Use Javadoc — Larger projects should make use of Javadoc for documentation. The Javadoc command parses source code declarations and documentation comments and produces a set of HTML pages that describes all public and protected classes, interfaces, constructors, methods, and fields.


  • Indents — Four spaces should be the standard unit of indentation. You code should be consistent thoughout the code base. Make sure you convert tabs to spaces, using your IDE’s functionality to assist in the indentation.
  • Block Indentation (2 spaces) — Every time a new block is opened, we indent by two spaces. When the block ends we immediately return to the previous indentation level. Using this methodology, blocks of code are easily identified and will make your code clearer and more concise.
public void MyMethod() {
  if (condition1()) {
    try {
    } catch (Exception e) {
  } else if (condition2()) {
  } else {

White Space

  • Blank Lines — Use blank lines to improve the readability of the code.
    • Between package and import statements
    • Between variables and first statement
    • Methods should have blank lines preceding them.
    • Before each discrete logical section of code to improve readability
package com.avaldes.tutorial;

import java.text.DateFormat;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;

public class RestController {

  private static final Logger logger = LoggerFactory

  private IssuerRepository issuerRepository;

  @RequestMapping(value="/issuers", method=RequestMethod.GET)
  public multipleIssuerResponse getAllIssuers() {
  • Blank Spaces — Blank spaces should be used when required (after keywords) and for added readability
    • keywords followed by a parenthesis should be separated by a space (if, for, while, switch, …)
    • space after comma for each parameter in the list
    • space after assignments and other operators
    • space after Casts
// Spaces for readability
String[] names = {"Amaury", "John", "James", "Marie"};
//Spaces required after keywords like 'for' loops
for (String name : names) {
  System.out.println("value is " + name);
// Spaces after casts - assume Ferrari extends Car
Car c = new Car();
Car myCar;
Ferrari f = new Ferrari ();
myCar = (Ferrari) c; // Explicit Cast car to Ferrari


  • Braces — Braces should be used with if, else, for, do and while statements even for single statements. Use the Kernighan and Ritchie (K & R) style of brackets
    • No line breaks before the opening brace
    • Line breaks after the opening brace
    • Line break before the closing brace
    • Linke break after the closing brace
public void MyMethod() {
  if (condition1()) {
    try {
    } catch (Exception e) {
  } else if (condition2()) {
  } else {


Please ensure you always show exceptions in the catch block.

try {
} catch (Exception e) {}

if Statements

  • The if statment and conditional expression is placed on the same line and braces are used to define the scope. The ‘if’ keyword is followed by a space and the condition is placed in parenthesis, followed by another space and the opening brace. The statement or statements are placed in individual lines below using the proper indentation. The ending curly brace starts in a new line using the same indentation of the opening curly brace for that ‘if’ statement.
if (condition) {
} else {

for statement

  • The for statement provides a quick and effective way to iterate over a range of values. It is often called a for loop by developers.
for (initialization; condition; increment/decrement) {
  • In the next example, the variable ‘i’ is both instantiated and initialized to one (1). It is important to note that the scope of this variable ‘i’ is limited to the opening curly brace and ending curly brace.
for (int i=1; i<=10; i++) {

Infinite Loops

// Infinite For Loop
for (;;) {

// Infinite While Loop
while (true) {

// Infinite Do-While Loop
do {
} while (true);

while Statements

  • The while statement follows the same format as the ‘if’ construct. The ‘while’ keyword is followed by a space and the condition is placed in parenthesis, followed by another space and the opening brace. The statement or statements are placed in individual lines below using the proper indentation. The ending curly brace starts in a new line using the same indentation of the opening curly brace for that ‘while’ statement.
while (condition) {

do-while Statements

  • The do-while statement follows the same format as the ‘while’ construct. The only caveat is that the condition follows the closing curly brace as shown below.

    NOTE: The only time you want to use the do-while loop is when you want the execution of the statements to take place at least one time, otherwise the better choice is always the while loop.
do {
} while (condition);

switch Statements

  • The switch statement allows you to have multiple possible execution paths. The switch statement works with multiple primative types (byte, short, char and int). Additionally, it allows you to work with Enum types, String, Character, Byte, Short and Integer wrapper classes.
switch (condition) {
case A:
case B:
case C:
    // missing break -- will run case C / case D statements
case D:

try-catch-finally Statements

  • The try-catch statements are used to catch exceptions in your Java code. You can catch multiple exceptions in one try-catch block of code. Each subsequent catch block will define a different exception type that will be handled. The exception type must be the name of the class that inherits from Throwable class.
try {
} catch (IOException ex1) {
   logger.error("IOException found: {}", ex1);
   throw ex;
} catch (SQLException ex2) {
   logger.error("SQLException found: {}", ex2);
   throw ex;
} catch (Exception ex3) {
   logger.error("Exception found: {}", ex3);
   throw ex;

Java 7 and later

The catch block can now handle multiple exceptions in a single catch block separated with a pipe symbol (|).

try {
} catch (IOException|SQLException ex) {
    throw ex;


Java Arrays are containers that hold a fixed number of homogeneous elements. In other words, all of the data elements in the array are of the same data type. We define the length of the array when it is created. Each of the items in an array is called an element. These elements are each accessed by their numerical index beginning with index = 0.


Say we have an array of 10 elements, we would have index range from 0 through 9.

Declaring Array in Java

Declaring Java arrays follows the same conventions as when we declare variables of other types. We write the array as the type[]; the brackets [] are used to indicate that the variables holds an array. This is followed by the array’s name, which is whatever you like to call it, provided you follow standard naming conventions. For more on informaion on variable naming conventions, please refer to a previous post called, “Java Tutorial – Language Syntax and Structure”.

Declaring an array in Java has two formats; the developers have the option of using one of the following syntax:

Standard Convention

array_type[] array_name;

int[] arrayOfInts;      // array of int primitives<br>
long[] nationalDebt;    // array of long primitives<br>
boolean[] isActive;     // array of boolean primitives<br>
char[] arrayOfChars;    // array of char primitives<br>
String[] arrayOfString; // array of String objects<br>


Non-Standard Convention

array_type array_name[];

short gamesPlayed[];  // array of short primitives<br>

As you can see from the above examples, using the standard convention makes it easier to identify the array of a certain type when the brackets are next to the type assignment.

At this point, you will note that array size has not been defined. This means that the array array_name can be assigned any length. This will be explained shortly in the next section.

Instantiating an Array in Java

When we declared the array previously, we actually did not create the array. We only instructed the Java compiler that the variable we declared will hold an array of a certain type. Instantiating an array happens when we use the new operator.

new type[size];

int[] arrayOfInts;<br>
char[] arrayOfChars;<br>
String[] arrayOfString;</p>
<p>arrayOfInts = new int[20];<br>
arrayOfChars = new char[100];<br>
arrayOfString = new String[100];</p>
<p>arrayOfString[0] = "Amaury Valdes";<br>
arrayOfString[1] = "Stacy Wilder";<br>
arrayOfString[2] = "Jane Hoffman";<br>
arrayOfString[99] = "Bill Bradley";<br>

In this example, we create three separate arrays. The first example creates an array of int 20 primitives. These primitives are all created with the default value of 0 (for int). The second array is created with a size of 100, and will be defaulted to ‘\u0000’ (for char). The final array of type String is created with a size of 100, and will be defaulted to null (for String).

We reference array elements by using an index. Please note that for arrays of size n, the valid indexes are between 0 and n-1.


We can alternately declare and instantiate (create) arrays in one line.

int[] arrayOfInts = new int[20];<br>
char[] arrayOfChars = new char[100];<br>
String[] arrayOfString = new String[100];<br>

Please Note

Be careful when referencing arrays using the index as using a negative number or a number greater than the array size will generate a java.lang.ArrayIndexOutOfBoundsException.

Negative Array Size Exception

The java.lang.NegativeArraySizeException is an exception you will rarely see as it will only occur if you accidentally instantiate an array with an array size of negative number.

This may occur if the developer, for example, were assigning the size based on some computational calculation and the value somehow became negative.

That’s It!

I hope you enjoyed this post. It was certainly a lot of fun putting it together for you. Please continue to share the love and like us so that we can continue bringing you quality posts and tutorials. Happy Coding!!!

Core Java Related Tutorials

Please Share Us on Social Media


Leave a Reply

Your email address will not be published. Required fields are marked *