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.
CONSTANT_VARIABLE
public class ClassName {…}
Source Code Guidelines
Comments
- 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, avaldes.com All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * 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.
Indentation
- 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 { doSomethingCondition1(); } catch (Exception e) { showException(); } } else if (condition2()) { doSomethingCondition2(); } else { doFallback(); } }
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; @Controller public class RestController { private static final Logger logger = LoggerFactory .getLogger(RestController.class); @Autowired private IssuerRepository issuerRepository; @RequestMapping(value="/issuers", method=RequestMethod.GET) @ResponseBody 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 — 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 { doSomethingCondition1(); } catch (Exception e) { showException(); } } else if (condition2()) { doSomethingCondition2(); } else { doFallback(); } }
DON’T DO THIS
Please ensure you always show exceptions in the catch block.
try { doSomethingCondition1(); } 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) { statement1 } else { statement2 }
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) { statement }
- 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++) { statement }
Infinite Loops
// Infinite For Loop for (;;) { statement } // Infinite While Loop while (true) { statement } // Infinite Do-While Loop do { statement } 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) { statement }
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 { statement } 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: statements; break; case B: statements; break; case C: statements; // missing break -- will run case C / case D statements case D: statements; break; default: statements; break; }
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 { doSomeIOProcessing(); } 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 { doSomeIOProcessing(); } catch (IOException|SQLException ex) { logger.log(ex); throw ex; }
Arrays
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

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
<br> 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>
or
Non-Standard Convention
<br> 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.
<br> 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> ...<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.
<br> 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
- Base64 Encoding and Decoding Examples in Java 8
In this tutorial we will discuss how to Encode and Decode using Base64 using Java 8, which now finally has native Base64 support. - Base64 Encoding and Decoding Examples in Java using Google Guava
This tutorial will introduce how to Encode and Decode using Base64 using Google’s Guava Project Open Source library. - Base64 Encoding and Decoding Examples in Java using Apache Commons
This tutorial will introduce Base64 encoding and decoding examples using the Apache Commons Codec library. - Custom Number Formatting in Java
In this example we will show you how to use the NumberFormat and DecimalFormat classes to format numbers using special patterns. - Custom Date Formatting in Java
In this example we will show you how to use the SimpleDateFormat class to format Date objects using special patterns to better fit the needs of the application.
Please Share Us on Social Media






Leave a Reply