Skip to main content

Java Coding Violations


Avoid Branching Statement As Last In Loop

Description: Using a branching statement as the last part of a loop may be a bug, and/or is confusing

Label Label Label

Bad Example
for (int j = 0; j < 5; j++) {
if (j*j <= 12) {
continue;
}
break;
}
Good Example
for (int j = 0; j < 5; j++) {
if (j*j > 12) {
break;
}
}

Avoid Decimal Literals In Big Decimal Constructor

Description: "One might assume that the result of ""new BigDecimal(0.1)"" is exactly equal to 0.1, but it is not because 0.1 cannot be represented exactly as a double (or as a binary fraction of any finite length)"

Label Label Label

Bad Example
BigDecimal bd = new BigDecimal(2.456);
Good Example
BigDecimal bd = new BigDecimal("2.456");

Avoid Multiple Unary Operators

Description: Avoid Multiple Unary Operators

Label Label Label

Bad Example
int k = - -1;
int l = + - +1;
int m = ~~4;
boolean a = !!true;
boolean b = !!!true;

Avoid Thread Group

Description: Avoid using java.lang.ThreadGroup. Although it is intended to be used in a threaded environment it contains methods that are not thread-safe

Label Label Label

Bad Example
public class Beta {
void beta() {
ThreadGroup tg = new ThreadGroup("My threadgroup");
tg = new ThreadGroup(tg, "my thread group");
tg = Thread.currentThread().getThreadGroup();
tg = System.getSecurityManager().getThreadGroup();
}
}

Avoid Using Hard Coded IP

Description: Application with hard-coded IP addresses can become impossible to deploy in some cases. Externalizing IP adresses is preferable

Label Label Label

Bad Example
public class Alpha {
private String ip = "127.0.0.1";
}

Avoid Using Octal Values

Description: Integer literals should not start with zero since this denotes that the rest of literal will be interpreted as an octal value

Label Label Label

Bad Example
int i = 010;
Good Example
int i = 10;

Big Integer Instantiation

Description: Don’t create instances of already existing BigInteger

Label Label Label

Bad Example
BigInteger bf = new BigInteger(1);
Good Example
bf = BigInteger.ONE;

Boolean Instantiation

Description: Avoid instantiating Boolean objects

Label Label Label

Bad Example
Boolean foo = new Boolean("true"); 

Broken Null Check

Description: The null check is broken since it will throw a NullPointerException itself

Label Label Label

Bad Example
public String foo(String string) {
if (string!=null || !string.equals(""))
return string;
if (string==null && string.equals(""))
return string;
}
Good Example
public String foo(String string) {
if (string!=null && !string.equals(""))
return string;
if (string==null || string.equals(""))
return string;
}

Check Result Set

Description: Always check the return values of navigation methods (next, previous, first, last) of a ResultSet. If the value return is ‘false’, it should be handled properly

Label Label Label

Bad Example
Statement stat = conn.createStatement();
ResultSet rst = stat.executeQuery("SELECT testvalue FROM testtable");
rst.next();
String testName = rst.getString(1);
Good Example
Statement stat = conn.createStatement();
ResultSet rst = stat.executeQuery("SELECT name FROM person");
if (rst.next()) {
String firstName = rst.getString(1);
} else {
// handle else
}

Check Skip Result

Description: The skip() method may skip a smaller number of bytes than requested

Label Label Label

Bad Example
public class Alpha {

private FileInputStream _s = new FileInputStream("file");

public void skip(int n) throws IOException {
_s.skip(n);
}
}
Good Example
public class Alpha {

private FileInputStream _s = new FileInputStream("file");

public void skip(int n) throws IOException {
_s.skip(n);
}

public void skipExactly(int n) throws IOException {
while (n != 1) {
long skipped = _s.skip(n);
if (skipped == 1)
throw new EOFException();
n -= skipped;
}
}
}

Class Cast Exception With To Array

Description: When deriving an array of a specific class from your Collection, one should provide an array of the same class as the parameter of the toArray() method. Doing otherwise you will will result in a ClassCastException

Label Label Label

Bad Example
Collection a = new ArrayList();
Integer obj = new Integer(1);
a.add(obj);
Integer[] b = (Integer [])a.toArray();
Good Example
Collection a = new ArrayList();
Integer obj = new Integer(1);
a.add(obj);
Integer[] b = (Integer [])a.toArray(new Integer[a.size()]);

Collapsible If Statements

Description: Sometimes two consecutive ‘if’ statements can be consolidated by separating their conditions with a boolean short-circuit operator

Label Label Label

Bad Example
void foo() {
if (a) {
if (b) {
// doSomething
}
}
}
Good Example
void foo() {
if (a && b) {
// doSomething
}
}

Explicitly calling Thread.run()

Description: Explicitly calling Thread.run() method will execute in the caller’s thread of control. Instead, call Thread.start() for the intended behavior

Label Label Label

Bad Example
Thread a = new Thread();
a.run();
Good Example
Thread a = new Thread();
a.start();

Dont Use Float Type For Loop Indices

Description: Don’t use floating point for loop indices

Label Label Label

Bad Example
public class Count {
public static void main(String[] args) {
final int START = 5000000000;
int count = 0;
for (float f = START; f < START + 50; f++)
count++;
System.out.println(count);
}
}

Double Checked Locking

Description: Partially created objects can be returned by the Double Checked Locking pattern when used in Java

Label Label Label

Bad Example
public class Alpha {
Object beta = null;
Object gamma() {
if (beta == null) {
synchronized(this) {
if (beta == null) {
beta = new Object();
}
}
}
return beta;
}
}
Good Example
public class Alpha {
/*volatile */ Object beta = null;
Object gamma() {
if (beta == null) {
synchronized(this) {
if (beta == null) {
beta = new Object();
}
}
}
return beta;
}
}

Empty Catch Block

Description: Empty Catch Block finds instances where an exception is caught, but nothing is done

Label Label Label

Bad Example
public void doThis() {
try {
FileInputStream fil = new FileInputStream("/tmp/test");
} catch (IOException ioe) {
}
}

Empty Finally Block

Description: Empty finally blocks serve no purpose and should be removed

Label Label Label

Bad Example
public class Alpha {
public void beta() {
try {
int x = 5;
} finally {
// empty!
}
}
}
Good Example
public class Alpha {
public void beta() {
try {
int x = 5;
}
}
}

Empty If Stmt

Description: Empty If Statement finds instances where a condition is checked but nothing is done about it

Label Label Label

Bad Example
public class Alpha {
void beta(int y) {
if (y == 2) {
// empty!
}
}
}
Good Example
public class Alpha {
void beta(int y) {
if (y == 2) {
//doSomething
}
}
}

Empty Statement Block

Description: Empty block statements serve no purpose and should be removed.

Label Label Label

Bad Example
public class Alpha {

private int _beta;

public void setBeta(int beta) {
{ _beta = beta; }
{}
}

}
Good Example
public class Alpha {

private int _beta;

public void setBeta(int beta) {
{ _beta = beta; }
}

}

Empty Statement Not In Loop

Description: An empty statement (or a semicolon by itself) that is not used as the sole body of a ‘for’ or ‘while’ loop is probably a bug

Label Label Label

Bad Example
public void doThis() {
System.out.println("look at the extra semicolon");;
}
Good Example
public void doThis() {
System.out.println("look at the extra semicolon");
}

Empty Static Initializer

Description: Empty initializers serve no purpose and should be removed

Label Label Label

Bad Example
public class Alpha {
static {}
}
Good Example
public class Alpha {
static {
//doSomething
}
}

Empty Switch Statements

Description: Empty switch statements serve no purpose and should be removed

Label Label Label

Bad Example
public void beta() {
int a = 5;
switch (a) {}
}
Good Example
public void beta() {
int a = 5;
switch (a) {
//doSomething
}
}

Empty Synchronized Block

Description: Empty synchronized blocks serve no purpose and should be removed

Label Label Label

Bad Example
public class Alpha {
public void beta() {
synchronized (this) {
}
}
}
Good Example
public class Alpha {
public void beta() {
synchronized (this) {
//doSomething
}
}
}

Empty Try Block

Description: Avoid empty try blocks

Label Label Label

Bad Example
public class Alpha {
public void beta() {
try {
} catch (Exception e) {
e.printStackTrace();
}
}
}

Empty While Stmt

Description: Empty While Statement finds all instances where a while statement does nothing.If it is a timing loop, then you should use Thread.sleep() for it

Label Label Label

Bad Example
void beta(int x, int y) {
while (x == y) {
}
}
Good Example
void beta(int x, int y) {
while (x == y) {
//doSomething
}
}

Extends Object

Description: No need to explicitly extend Object

Label Label Label

Bad Example
public class Alpha extends Object {
}

For Loop Should Be While Loop

Description: Some for loops can be simplified to while loops, this makes them more concise

Label Label Label

Bad Example
public class Alpha {
void beta() {
for (;true;) true;
}
}
Good Example
public class Alpha {
void beta() {
while (true) true;
}
}

Jumbled Incrementer

Description: Avoid jumbled loop incrementers - its usually a mistake, and is confusing even if intentional

Label Label Label

Bad Example
public class Alpha {
public void beta() {
for (int j = 0; j < 5; j++) {
for (int k = 0; k < 12; j++) {
System.out.println("Hello World");
}
}
}
}
Good Example
public class Alpha {
public void beta() {
for (int j = 0; j < 5; j++) {
for (int k = 0; k < 12; k++) {
System.out.println("Hello World");
}
}
}
}

Misplaced Null Check

Description: "The null check here is misplaced. If the variable is null a NullPointerException will be thrown. Either the check is useless (the variable will never be ""null"") or it is incorrect"

Label Label Label

Bad Example
public class Alpha {
void beta() {
if (b.equals(theta) && b != null) {}
}
}
Good Example
public class Alpha {
void beta() {
if (b == null && b.equals(theta)) {}
}
}

Override Both Equals And Hashcode

Description: Override both public boolean Object.equals(Object other), and public int Object.hashCode(), or override neither

Label Label Label

Bad Example
public class Alpha {
public boolean equals(Object a) {
//someComparison
}
}
Good Example
public class Alpha {
public boolean equals(Object b) {
// someComparison
}
public int hashCode() {
// return hash value
}
}

Return From Finally Block

Description: Avoid returning from a finally block, this can discard exceptions

Label Label Label

Bad Example
public class Alpha {
public String beta() {
try {
throw new Exception( "Exception" );
} catch (Exception e) {
throw e;
} finally {
return "This";
}
}
}
Good Example
public class Alpha {
public String beta() {
try {
throw new Exception( "Exception" );
} catch (Exception e) {
throw e;
} finally {
//doSomething
}
}
}

Unconditional If Statement

Description: "Do not use ""if"" statements whose conditionals are always true or always false"

Label Label Label

Bad Example
public class Alpha {
public void close() {
if (false) {
//doSomething
}
}
}
Good Example
public class Alpha {
public void close() {
//doSomething
}
}

Unnecessary Conversion Temporary

Description: Avoid the use temporary objects when converting primitives to Strings. Use the static conversion methods on the wrapper classes instead

Label Label Label

Bad Example
public String convert(int a) {
String alpha = new Integer(a).toString();
}
Good Example
public String convert(int a) {
return Integer.toString(a);
}

Unused Null Check In Equals

Description: After checking an object reference for null, you should invoke equals() on that object rather than passing it to another object’s equals() method

Label Label Label

Bad Example
public class Alpha {

public String alpha1() { return "done";}
public String alpha2() { return null;}

public void method(String x) {
String y;
if (x!=null && alpha1().equals(x)) {
//doSomething
}
}
}
Good Example
public class Alpha {

public String alpha1() { return "done";}
public String alpha2() { return null;}

public void method(String x) {
String y;
if (x!=null && alpha1().equals(y)) {
//doSomething
}
}
}

Useless Operation On Immutable

Description: An operation on an Immutable object (String, BigDecimal or BigInteger) won’t change the object itself since the result of the operation is a new object

Label Label Label

Bad Example
class Alpha {
void alpha1() {
BigDecimal bd=new BigDecimal(20);
bd.add(new BigDecimal(4));
}
}
Good Example
class Alpha {
void alpha1() {
BigDecimal bd=new BigDecimal(20);
bd = bd.add(new BigDecimal(4));
}
}

Useless Overriding Method

Description: The overriding method merely calls the same method defined in a superclass

Label Label Label

Bad Example
public void alpha(String beta) {
super.alpha(beta);
}
Good Example
public Long getId() {
return super.getId();
}

For Loops Must Use Braces

Description: For Loops Must Use Braces

Label Label Label

Bad Example
for (int j = 0; j < 34; j++)
alpha();
Good Example
for (int j = 0; j < 34; j++) {
alpha()
};

If Else Stmts Must Use Braces

Description: If Else Stmts Must Use Braces

Label Label Label

Bad Example
if (alpha)
i = i + 1;
else
i = i - 1;
Good Example
if (alpha) {
i = i + 1;
} else {
i = i - 1;
}

If Stmts Must Use Braces

Description: If Stmts Must Use Braces

Label Label Label

Bad Example
if (alpha)
i++;
Good Example
if (alpha) {
i++;
}

While Loops Must Use Braces

Description: While Loops Must Use Braces

Label Label Label

Bad Example
while (true)
i++;
Good Example
while (true) {
i++;
}

Clone Throws Clone Not Supported Exception

Description: The method clone() should throw a CloneNotSupportedException

Label Label Label

Bad Example
public class Alpha implements Cloneable{
public Object clone() {
Alpha clone = (Alpha)super.clone();
return clone;
}
}

Proper Clone Implementation

Description: Object clone() should be implemented with super.clone()

Label Label Label

Bad Example
class Alpha{
public Object clone(){
return new Alpha();
}
}

Assignment In Operand

Description: Avoid assignments in operands. This can make code more complicated and harder to read

Label Label Label

Bad Example
public void beta() {
int a = 2;
if ((a = getA()) == 3) {
System.out.println("3!");
}
}

Avoid Accessibility Alteration

Description: Methods such as getDeclaredConstructors(), getDeclaredConstructor(Class[]) and setAccessible(), as the interface PrivilegedAction, allow for the runtime alteration of variable, class, or method visibility, even if they are private. This violates the principle of encapsulation

Label Label Label

Bad Example
public class Violation {
private void invalidSetAccessCalls() throws NoSuchMethodException, SecurityException {
Constructor<?> constructor = this.getClass().getDeclaredConstructor(String.class);
constructor.setAccessible(true);

Method privateMethod = this.getClass().getDeclaredMethod("aPrivateMethod");
privateMethod.setAccessible(true);
}
}

Avoid Prefixing Method Parameters

Description: Prefixing parameters by ‘in’ or ‘out’ pollutes the name of the parameters and reduces code readability

Label Label Label

Bad Example
public class Alpha {
public void beta(
int inLeftOperand,
Result outRightOperand) {
outRightOperand.setValue(inLeftOperand * outRightOperand.getValue());
}
}
Good Example
public class Alpha {
public void beta(
int leftOperand,
Result rightOperand) {
rightOperand.setValue(leftOperand * rightOperand.getValue());
}
}

Avoid Using Native Code

Description: Unnecessary reliance on Java Native Interface (JNI) calls directly reduces application portability and increases the maintenance burden

Label Label Label

Bad Example
public class SomeNativeClass {
public SomeNativeClass() {
System.loadLibrary("nativelib");
}

static {
System.loadLibrary("nativelib");
}

public void invalidCallsInMethod() throws SecurityException, NoSuchMethodException {
System.loadLibrary("nativelib");
}
}

Default Package

Description: Use explicit scoping instead of accidental usage of default package private level

Label Label Label

Bad Example
File saveFile = new File("C:/Upload/");
Good Example
private File saveFile = new File("C:/Upload/");

Do Not Call Garbage Collection Explicitly

Description: Calls to System.gc(), Runtime.getRuntime().gc(), and System.runFinalization() are not advised. Code should have the same behavior whether the garbage collection is disabled using the option -Xdisableexplicitgc or not

Label Label Label

Bad Example
public class AlphaGC {
public explicitAlphaGC() {
// Explicit garbage collector call
System.gc();
}
}

Dont Import Sun

Description: Avoid importing anything from the ‘sun.*’ packages. These packages are not portable and are likely to change

Label Label Label

Bad Example
import sun.misc.bar;

One Declaration Per Line

Description: Java allows the use of several variables declaration of the same type on one line. However, it can lead to quite messy code

Label Label Label

Bad Example
String first, last;
Good Example
String first;
String last;

Suspicious Octal Escape

Description: A suspicious octal escape sequence was found inside a String literal

Label Label Label

Bad Example
public void beta() {
System.out.println("suspicious: \128");
}

Unnecessary Constructor

Description: When there is only one constructor and the constructor is identical to the default constructor, then it is not necessary

Label Label Label

Bad Example
public class Alpha {
public Alpha() {}
}
Good Example
public class Alpha {
public Beta() {}
}

Abstract Class Without Abstract Method

Description: The abstract class does not contain any abstract methods. An abstract class suggests an incomplete implementation, which is to be completed by subclasses implementing the abstract methods

Label Label Label

Bad Example
public abstract class Alpha {
void int method1() { ... }
void int method2() { ... }
}

Abstract Class Without Any Method

Description: If an abstract class does not provides any methods, it may be acting as a simple data container that is not meant to be instantiated

Label Label Label

Bad Example
public abstract class Alpha {
String field;
int otherField;
}

Assignment To Non Final Static

Description: Possible unsafe usage of a static field

Label Label Label

Bad Example
public class StaticField {
static int a;
public FinalFields(int b) {
a = b;
}
}

Avoid Constants Interface

Description: Avoid constants in interfaces. Interfaces should define types, constants are implementation details better placed in classes or enums

Label Label Label

Bad Example
public interface AlphaInterface {
public static final int CONST1 = 1;
static final int CONST2 = 1;
final int CONST3 = 1;
int CONST4 = 1;
}
Good Example
public interface BetaInterface {
public static final int CONST1 = 1;

int anyMethod();
}

Avoid Instanceof Checks In Catch Clause

Description: Each caught exception type should be handled in its own catch clause

Label Label Label

Bad Example
try {
//doSomething
} catch (Exception ee) {
if (ee instanceof IOException) {
cleanup();
}
}
Good Example
try {
//doSomething
} catch (IOException ee) {
cleanup();
}

Avoid Protected Field In Final Class

Description: Do not use protected fields in final classes since they cannot be subclassed

Label Label Label

Bad Example
public final class Alpha {
private int a;
protected int b;
Alpha() {}
}
Good Example
public final class Alpha {
private int a;
private int b;
Alpha() {}
}

Avoid Protected Method In Final Class Not Extending

Description: Do not use protected methods in most final classes since they cannot be subclassed

Label Label Label

Bad Example
public final class Alpha {
private int beta() {}
protected int beta() {}
}
Good Example
public final class Alpha {
private int beta() {}
private int beta() {}
}

Avoid Reassigning Parameters

Description: Reassigning values to incoming parameters is not recommended. Use temporary local variables instead

Label Label Label

Bad Example
public class Boo {
private void boo(String tab) {
tab = "changed string";
}
}
Good Example
public class Boo {
private void foo(String tab) {
String tab2 = String.join("A local value of tab: ", tab);;
}
}

Avoid Synchronized At Method Level

Description: Method-level synchronization can cause problems when new code is added to the method. Block-level synchronization helps to ensure that only the code that needs synchronization gets it

Label Label Label

Bad Example
public class Alpha {
synchronized void alpha() {
}
}
Good Example
public class Alpha {
void beta() {
synchronized(this) {
}
}

Bad Comparison

Description: BadComparison

Label Label Label

Bad Example
boolean x = (y == Double.NaN);

Class With Only Private Constructors Should Be Final

Description: Avoid equality comparisons with Double.NaN due to the implicit lack of representation precision

Label Label Label


Close Resource

Description: Ensure that resources (like java.sql.Connection, java.sql.Statement, and java.sql.ResultSet objects and any subtype of java.lang.AutoCloseable) are always closed after use. Failing to do so might result in resource leaks

Label Label Label

Bad Example
public class Beta {
public void alpha() {
Connection a = pool.getConnection();
try {
// doSomething
} catch (SQLException ex) {
//exception
} finally {
//forgotToClose
}
}
}
Good Example
public class Beta {
public void alpha() {
Connection a = pool.getConnection();
try {
// doSomething
} catch (SQLException ex) {
//exception
} finally {
a.close();
}
}
}

Constructor Calls Overridable Method

Description: Calling overridable methods during construction poses a risk of invoking methods on an incompletely constructed object and can be difficult to debug

Label Label Label

Bad Example
public class SeniorClass {
public SeniorClass() {
toString();
}
public String toString(){
return "ThatSeniorClass";
}
}
public class JuniorClass extends SeniorClass {
private String name;
public JuniorClass() {
super();
name = "JuniorClass";
}
public String toString(){
return name.toUpperCase();
}
}

Default Label Not Last In Switch Stmt

Description: By convention, the default label should be the last label in a switch statement

Label Label Label

Bad Example
public class Alpha {
void beta(int x) {
switch (x) {
case 1: // doSomething
break;
default:
break;
case 2:
break;
}
}
}
Good Example
public class Alpha {
void beta(int x) {
switch (x) {
case 1: // doSomething
break;
case 2:
break;
default:
break;
}
}
}

Empty Method In Abstract Class Should Be Abstract

Description: Empty or auto-generated methods in an abstract class should be tagged as abstract

Label Label Label

Bad Example
public abstract class NeedsToBeAbstract {
public Object mayBeAbstract() {
return null;
}
}
Good Example
public abstract class NeedsToBeAbstract {
public void mayBeAbstract() {
}
}

Equals Null

Description: Tests for null should not use the equals() method. The ‘==’ operator should be used instead

Label Label Label

Bad Example
String a = "alpha";

if (a.equals(null)) {
doSomething();
}
Good Example
String a = "alpha";

if (a == null) {
doSomething();
}

Field Declarations Should Be At Start Of Class

Description: Fields should be declared at the top of the class, before any method declarations, constructors, initializers or inner classes

Label Label Label

Bad Example
public class Alpha {

public String getMessage() {
return "Hello";
}
private String _something;
}
Good Example
public class Alpha {
private String _fieldSomething;
public String getMessage() {
return "Hello";
}
}

Final Field Could Be Static

Description: If a final field is assigned to a compile-time constant, it could be made static, thus saving overhead in each object at runtime

Label Label Label

Bad Example
public class Alpha {
public final int BETA = 18;
}
Good Example
public class Alpha {
public static final int BETA = 18;
}

Idempotent Operations

Description: Avoid idempotent operations - they have no effect

Label Label Label

Bad Example
public class Alpha {
public void beta() {
int a = 10;
a = a;
}
}
Good Example
public class Alpha {
public void beta() {
int a = 10;
}
}

Immutable Field

Description: Private fields whose values never change once object initialization ends either in the declaration of the field or by a constructor should be final

Label Label Label

Bad Example
public class Alpha {
private int x; // could be final
public Alpha() {
x = 7;
}
public void alpha() {
int a = x + 2;
}
}

Instantiation To Get Class

Description: Avoid instantiating an object just to call getClass() on it use the .class public member instead

Label Label Label

Bad Example
Class a = new String().getClass();
Good Example
Class a = String.class;

Logic Inversion

Description: Use opposite operator instead of negating the whole expression with a logic complement operator

Label Label Label

Bad Example
public boolean beta(int x, int y) {
if (!(x == y)) {
return false;
}
return true;
}
Good Example
public boolean beta(int x, int y) {
if (x != y) {
return false;
}
return true;
}

Missing Break In Switch

Description: Switch statements without break or return statements for each case option may indicate problematic behaviour. Empty cases are ignored as these indicate an intentional fall-through

Label Label Label

Bad Example
public void alpha(int status) {
switch(status) {
case CANCELLED:
doSomething();
// break;
case OTHER:
case ERROR:
doSomethingElse();
break;
}
}
Good Example
public void alpha(int status) {
switch(status) {
case CANCELLED:
doSomething();
break;
case ERROR:
doSomethingElse();
break;
}
}

Missing Static Method In Non Instantiatable Class

Description: A class that has private constructors and does not have any static methods or fields cannot be used

Label Label Label

Bad Example
public class Alpha {
private Alpha() {}
void Alpha() {}
}
Good Example
public class Alpha {
public static void main(String[] args) {
doSomething
}
}

Non Case Label In Switch Statement

Description: A non-case label (e.g. a named break/continue label) was present in a switch statement. This legal, but confusing. It is easy to mix up the case labels and the non-case labels

Label Label Label

Bad Example
public class Alpha {
void beta(int x) {
switch (x) {
case 1:
doSomething;
break;
somelabel:
break;
default:
break;
}
}
}

Non Static Initializer

Description: A non-static initializer block will be called any time a constructor is invoked (just prior to invoking the constructor)

Label Label Label

Bad Example
public class Alpha {
{
System.out.println("Construct");
}
}

Non Thread Safe Singleton

Description: Non-thread safe singletons can result in bad state changes. Eliminate static singletons if possible by instantiating the object directly. Static singletons are usually not needed as only a single instance exists anyway

Label Label Label

Bad Example
private static Alpha alpha = null;
public static Alpha getAlpha() {
if (alpha == null) {
alpha = new Alpha();
}
return alpha;
}

Optimizable To Array Call

Description: Calls to a collection’s ‘toArray(E[])’ method should specify a target array of zero size

Label Label Label

Bad Example
Alpha[] alphaArray = alphas.toArray(new Alpha[alphas.size()]);
Good Example
Alpha[] alphaArray = alphas.toArray(new Alpha[0]);

Position Literals First In Case Insensitive Comparisons

Description: Position literals first in comparisons, if the second argument is null then NullPointerExceptions can be avoided, they will just return false

Label Label Label

Bad Example
class Alpha {
boolean beta(String a) {
return a.equalsIgnoreCase("2");
}
}
Good Example
class Alpha {
boolean beta(String a) {
return "2".equalsIgnoreCase(a);
}
}

Position Literals First In Comparisons

Description: Position literals first in comparisons, if the second argument is null then NullPointerExceptions can be avoided, they will just return false

Label Label Label

Bad Example
class Alpha {
boolean beta(String a) {
return a.equals("2");
}
}
Good Example
class Alpha {
boolean beta(String a) {
return "2".equals(a);
}
}

Preserve Stack Trace

Description: Throwing a new exception from a catch block without passing the original exception into the new exception will cause the original stack trace to be lost making it difficult to debug effectively

Label Label Label

Bad Example
public class Alpha {
void beta() {
try{
Integer.parseInt("x");
} catch (Exception e) {
throw new Exception(e.getMessage());
}
}
}
Good Example
public class Alpha {
void beta() {
try{
Integer.parseInt("x");
} catch (Exception e) {
throw new Exception(e);
}
try {
Integer.parseInt("x");
} catch (Exception e) {
throw (IllegalStateException)new IllegalStateException().initCause(e);
}
}
}

Return Empty Array Rather Than Null

Description: For any method that returns an array, it is a better to return an empty array rather than a null reference. This removes the need for null checking all results and avoids inadvertent NullPointerExceptions

Label Label Label

Bad Example
public class Alpha {
public int[] beta() {
//doSomething
return null;
}
}
Good Example
public class Alpha {
public String[] beta() {
//doSomething
return new String[0];
}
}

Simple Date Format Needs Locale

Description: Be sure to specify a Locale when creating SimpleDateFormat instances to ensure that locale-appropriate formatting is used

Label Label Label

Bad Example
public class Alpha {
// Should specify Locale.US (or whatever)
private SimpleDateFormat sdf = new SimpleDateFormat("pattern");
}

Simplify Boolean Expressions

Description: Avoid unnecessary comparisons in boolean expressions, they serve no purpose and impacts readability

Label Label Label

Bad Example
public class Beta {
private boolean beta = (isAlpha() == true);

public isAlpha() { return false;}
}
Good Example
public class Beta {
beta = isAlpha();
public isAlpha() { return false;}
}

Simplify Boolean Returns

Description: Avoid unnecessary if-then-else statements when returning a boolean. The result of the conditional test can be returned instead

Label Label Label

Bad Example
public boolean isBetaEqualTo(int a) {
if (beta == a) {
return true;
} else {
return false;
}
}
Good Example
public boolean isBetaEqualTo(int a) {
return beta == a;
}

Simplify Conditional

Description: No need to check for null before an instanceof. The instanceof keyword returns false when given a null argument

Label Label Label

Bad Example
class Alpha {
void beta(Object a) {
if (a != null && a instanceof Beta) {
//doSomething
}
}
}
Good Example
class Alpha {
void beta(Object a) {
if (a instanceof Beta) {
//doSomething
}
}
}

Singular Field

Description: Fields whose scopes are limited to just single methods do not rely on the containing object to provide them to other methods. They may be better implemented as local variables within those methods

Label Label Label

Bad Example
public class Alpha {
private int a;
public void alpha(int b) {
a = b + 2;
return a;
}
}
Good Example
public class Alpha {
public void alpha(int b) {
a = b + 2;
return a;
}
}

Switch Stmts Should Have Default

Description: All switch statements should include a default option to catch any unspecified values

Label Label Label

Bad Example
public void beta() {
int a = 5;
switch (a) {
case 1: int b = 2;
case 2: int b = 4;
}
}
Good Example
public void beta() {
int a = 5;
switch (a) {
case 1: int b = 2;
case 2: int b = 4;
default: break;
}
}

Too Few Branches For ASwitch Statement

Description: Switch statements are intended to be used to support complex branching behaviour. Using a switch for only a few cases is ill-advised, since switches are not as easy to understand as if-then statements

Label Label Label

Bad Example
public class Alpha {
public void beta() {
switch (a) {
case 1:
doSomething;
break;
default:
break;
}
}
}
Good Example
public class Alpha {
public void beta() {
if (something) {
doSomething;
}
}
}

Uncommented Empty Constructor

Description: By explicitly commenting empty constructors it is easier to distinguish between intentional (commented) and unintentional empty constructors

Label Label Label

Bad Example
public Alpha() {
}
Good Example
public Alpha() {
//somethingCommented
}

Uncommented Empty Method

Description: By explicitly commenting empty method bodies it is easier to distinguish between intentional (commented) and unintentional empty methods

Label Label Label

Bad Example
public void alpha() {
}
Good Example
public void alpha() {
//somethingCommented
}

Unnecessary Local Before Return

Description: Avoid the creation of unnecessary local variables

Label Label Label

Bad Example
public class Alpha {
public int alpha() {
int a = doSomething();
return a;
}
}
Good Example
public class Alpha {
public int alpha() {
return doSomething();
}
}

Unsynchronized Static Date Formatter

Description: SimpleDateFormat instances are not synchronized. Sun recommends using separate format instances for each thread. If multiple threads must access a static formatter, the formatter must be synchronized on block leve

Label Label Label

Bad Example
public class Alpha {
private static final SimpleDateFormat sdf = new SimpleDateFormat();
void beta() {
sdf.format();
}
}
Good Example
public class Alpha {
private static final SimpleDateFormat sdf = new SimpleDateFormat();
synchronized void alpha() {
sdf.format();
}
}

Use Collection Is Empty

Description: The isEmpty() method on java.util.Collection is provided to determine if a collection has any elements. Comparing the value of size() to 0 does not convey intent as well as the isEmpty() method

Label Label Label

Bad Example
public class Alpha {
void beta() {
List alpha = getList();
if (alpha.size() == 0) {
//doSomething
}
}
}
Good Example
public class Alpha {
void beta() {
List alpha = getList();
if (alpha.isEmpty()) {
//doSomething
}
}
}

Use Locale With Case Conversions

Description: When doing String::toLowerCase()/toUpperCase() conversions, use an explicit locale argument to specify the case transformation rules

Label Label Label

Bad Example
class Alpha {
if (a.toLowerCase().equals("list")) { }
}
Good Example
class Alpha {
String x = a.toLowerCase(Locale.EN);
}

Use Notify All Instead Of Notify

Description: Thread.notify() awakens a thread monitoring the object. If more than one thread is monitoring, then only one is chosen. The thread chosen is arbitrary and thus its usually safer to call notifyAll() instead

Label Label Label

Bad Example
void beta() {
a.notify();
}
Good Example
void beta() {
a.notifyAll();
}

Use Varargs

Description: Java 5 introduced the varargs parameter declaration for methods and constructors. This syntactic sugar provides flexibility for users of these methods and constructors, allowing them to avoid having to deal with the creation of an array

Label Label Label

Bad Example
public class Alpha {
public void alpha(String a, Object[] args) {
//doSomething
}
}
Good Example
public class Alpha {
public void alpha(String a, Object... args) {
//doSomething
}
}

Avoid Calling Finalize

Description: The method Object.finalize() is called by the garbage collector on an object when garbage collection determines that there are no more references to the object. It should not be invoked by application logic

Label Label Label

Bad Example
void alpha() {
Beta a = new Beta();
a.finalize();
}

Empty Finalizer

Description: Empty finalize methods serve no purpose and should be removed. Note that Oracle has declared Object.finalize() as deprecated since JDK 9

Label Label Label

Bad Example
public class Alpha {
protected void finalize() {}
}

Finalize Does Not Call Super Finalize

Description: If the finalize() is implemented, its last action should be to call super.finalize. Note that Oracle has declared Object.finalize() as deprecated since JDK 9

Label Label Label

Bad Example
protected void finalize() {
doSomething();
}
Good Example
protected void finalize() {
doSomething();
super.finalize();
}

Finalize Only Calls Super Finalize

Description: If the finalize() is implemented, it should do something besides just calling super.finalize(). Note that Oracle has declared Object.finalize() as deprecated since JDK 9

Label Label Label

Bad Example
protected void finalize() {
super.finalize();
}
Good Example
protected void finalize() {
doSomething();
super.finalize();
}

Finalize Overloaded

Description: Methods named finalize() should not have parameters. It is confusing and most likely an attempt to overload Object.finalize(). It will not be called by the VM

Label Label Label

Bad Example
public class Alpha {
protected void finalize(int x) {
}
}

Finalize Should Be Protected

Description: When overriding the finalize(), the new method should be set as protected. If made public, other classes may invoke it at inappropriate times

Label Label Label

Bad Example
public void finalize() {
//doSomething
}
Good Example
protected void finalize() {
//doSomething
}

Dont Import Java Lang

Description: Avoid importing anything from the package ‘java.lang’. These classes are automatically imported

Label Label Label

Bad Example
import java.lang.String;

Duplicate Imports

Description: Duplicate or overlapping import statements should be avoided

Label Label Label

Bad Example
import java.lang.String;
import java.lang.*;
Good Example
import java.lang.*;

Import From Same Package

Description: There is no need to import a type that lives in the same package

Label Label Label

Bad Example
package alpha;

import alpha.Beta;
Good Example
package alpha;

Too Many Static Imports

Description: If you overuse the static import feature, it can make your program unreadable and unmaintainable, polluting its namespace with all the static members you import

Label Label Label

Bad Example
import static Alpha;
import static Beta;
import static Theta;
import static Omicron;

Unnecessary Fully Qualified Name

Description: Import statements allow the use of non-fully qualified names. The use of a fully qualified name which is covered by an import statement is redundant

Label Label Label

Bad Example
public class Alpha {
private java.util.List list1;
private List list2;
}

Do Not Call System Exit

Description: Web applications should not call System.exit(), since only the web container or the application server should stop the JVM

Label Label Label

Bad Example
public void beta() {
System.exit(0);
}

Local Home Naming Convention

Description: The Local Home interface of a Session EJB should be suffixed by ‘LocalHome’

Label Label Label

Bad Example
public interface MissingProperSuffix extends javax.ejb.EJBLocalHome {}
Good Example
public interface MyBeautifulLocalHome extends javax.ejb.EJBLocalHome {}

Local Interface Session Naming Convention

Description: The Local Interface of a Session EJB should be suffixed by ‘Local’

Label Label Label

Bad Example
public interface MissingProperSuffix extends javax.ejb.EJBLocalObject {}
Good Example
public interface MyLocal extends javax.ejb.EJBLocalObject {}

MDBAnd Session Bean Naming Convention

Description: The EJB Specification states that any MessageDrivenBean or SessionBean should be suffixed by ‘Bean’

Label Label Label

Bad Example
public class MissingTheProperSuffix implements SessionBean {}
Good Example
public class SomeBean implements SessionBean{}

Remote Interface Naming Convention

Description: Remote Interface of a Session EJB should not have a suffix

Label Label Label

Bad Example
public interface BadSuffixSession extends javax.ejb.EJBObject {}

Remote Session Interface Naming Convention

Description: A Remote Home interface type of a Session EJB should be suffixed by ‘Home’

Label Label Label

Bad Example
public interface MissingProperSuffix extends javax.ejb.EJBHome {}
Good Example
public interface MyHome extends javax.ejb.EJBHome {} 

Static EJBField Should Be Final

Description: According to the J2EE specification, an EJB should not have any static fields with write access. However, static read-only fields are allowed

Label Label Label

Bad Example
public class SomeEJB extends EJBObject implements EJBLocalHome {
private static int CountB;
}
Good Example
public class SomeEJB extends EJBObject implements EJBLocalHome {
private static final int CountB;
}

JUnit Assertions Should Include Message

Description: JUnit assertions should include an informative message - i.e., use the three-argument version of assertEquals(), not the two-argument version

Label Label Label

Bad Example
public class Alpha extends Beta {
public void theta() {
assertEquals("alpha", "beta");
}
}
Good Example
public class Alpha extends Beta {
public void theta() {
assertEquals("Alpha does not equals beta", "alpha", "beta");
}
}

JUnit Spelling

Description: Some JUnit framework methods are easy to misspell

Label Label Label

Bad Example
import junit.framework.*;
public class Alpha extends Beta {
public void setup() {}
}
Good Example
import junit.framework.*;
public class Alpha extends Beta {
public void setUp() {}
}

JUnit Static Suite

Description: The suite() method in a JUnit test needs to be both public and static

Label Label Label

Bad Example
import junit.framework.*;

public class Alpha extends Beta {
public void suite() {}
}
Good Example
import junit.framework.*;

public class Alpha extends Beta {
public static void suite() {}
}

JUnit Test Contains Too Many Asserts

Description: Unit tests should not contain too many asserts. Many asserts are indicative of a complex test, for which it is harder to verify correctness

Label Label Label

Bad Example
public class Alpha extends Beta {
public void testAlpha() {
boolean myTheta = false;
assertFalse("myTheta should be false", myTheta);
assertEquals("should equals false", false, myTheta);
}
}
Good Example
public class Alpha extends Beta {
public void testAlpha() {
boolean myTheta = false;
assertFalse("should be false", myTheta);
}
}

JUnit Tests Should Include Assert

Description: JUnit tests should include at least one assertion. This makes the tests more robust, and using assert with messages provide the developer a clearer idea of what the test does

Label Label Label

Bad Example
public class Foo extends TestCase {
public void testSomething() {
Bar b = findBar();
b.work();
}
}
Good Example
public class Foo extends TestCase {
public void testSomething() {
Bar b = findBar();
// This is better than having a NullPointerException
assertNotNull("bar not found", b);
}
}

Simplify Boolean Assertion

Description: Avoid negation in an assertTrue or assertFalse test

Label Label Label

Bad Example
assertTrue(!sth);
Good Example
assertFalse(sth);

Test Class Without Test Cases

Description: Test classes end with the suffix Test. Having a non-test class with that name is not a good practice, since most people will assume it is a test case

Label Label Label

Bad Example
public class CarTest {
public static void main(String[] args) {
}
}

Unnecessary Boolean Assertion

Description: A JUnit test assertion with a boolean literal is unnecessary since it always will evaluate to the same thing. Consider using flow control (in case of assertTrue(false) or similar) or simply removing statements like assertTrue(true) and assertFalse(false)

Label Label Label

Bad Example
public class Alpha extends Beta {
public void testAlpha() {
assertTrue(true);
}
}

Use Assert Equals Instead Of Assert True

Description: The assertions should be made by more specific methods, like assertEquals

Label Label Label

Bad Example
public class Alpha extends Beta {
void testAlpha() {
Object x, y;
assertTrue(x.equals(y));
}
}
Good Example
public class Alpha extends Beta {
void testAlpha() {
Object x, y;
assertEquals("x should equals y", x, y);
}
}

Use Assert Null Instead Of Assert True

Description: The assertions should be made by more specific methods, like assertNull, assertNotNull

Label Label Label

Bad Example
public class Alpha extends Beta {
void testAlpha() {
Object x = doSomething();
assertTrue(x == null);
}
}
Good Example
public class Alpha extends Beta {
void testAlpha() {
Object x = doSomething();
assertNull(x);
}
}

Use Assert Same Instead Of Assert True

Description: The assertions should be made by more specific methods, like assertSame, assertNotSame

Label Label Label

Bad Example
public class Alpha extends Beta {
void testAlpha() {
Object x, y;
assertTrue(x == y);
}
}
Good Example
public class Alpha extends Beta {
void testAlpha() {
Object x, y;
assertSame(x, y);
}
}

Use Assert True Instead Of Assert Equals

Description: When asserting a value is the same as a literal or Boxed boolean, use assertTrue/assertFalse, instead of assertEquals

Label Label Label

Bad Example
public class Alpha extends Beta {
public void testAlpha() {
boolean myTest = true;
assertEquals("myTest is true", true, myTest);
}
}
Good Example
public class Alpha extends Beta {
public void testAlpha() {
boolean myTest = true;
assertTrue("myTest is true", myTest);
}
}

Guard Debug Logging

Description: When log messages are composed by concatenating strings, the whole section should be guarded by a isDebugEnabled() check to avoid performance and memory issues

Label Label Label

Bad Example
logger.debug("This is a very long message that prints two values." +
" However since the message is long, we still incur the performance hit" +
" of String concatenation when logging {} and {}", value1, value2);
Good Example
if (logger.isDebugEnabled()) {
logger.debug("This is a very long message that prints two values." +
" However since the message is long, we still incur the performance hit" +
" of String concatenation when logging {} and {}", value1, value2);
}

Guard Log Statement

Description: Whenever using a log level, one should check if the loglevel is actually enabled, or otherwise skip the associate String creation and manipulation

Label Label Label

Bad Example
log.debug("logs here {} and {}", param1, param2);
Good Example
if (log.isDebugEnabled()) {
log.debug("logs here" + param1 + " and " + param2 + "concat strings");
}

Proper Logger

Description: A logger should normally be defined private static final and be associated with the correct class

Label Label Label

Bad Example
public class Alpha {
protected Log LOG = LogFactory.getLog(Testalpha.class);
}
Good Example
public class Alpha {
private static final Log LOG = LogFactory.getLog(Alpha.class);
}

Use Correct Exception Logging

Description: To make sure the full stacktrace is printed out, use the logging statement with two arguments: a String and a Throwable

Label Label Label

Bad Example
public class Alpha {
private static final Log _LOG = LogFactory.getLog( Alpha.class );
void beta() {
try {
} catch( Exception e ) {
_LOG.error( e );
}
}
}
Good Example
public class Alpha {
private static final Log _LOG = LogFactory.getLog( Alpha.class );
void beta() {
try {
} catch( OtherException oe ) {
_LOG.error( oe.getMessage(), oe );
}
}
}

Avoid Print Stack Trace

Description: Avoid printStackTrace() use a logger call instead

Label Label Label

Bad Example
class Alpha {
void beta() {
try {
//doSomething
} catch (Exception e) {
e.printStackTrace();
}
}
}

Guard Log Statement Java Util

Description: Whenever using a log level, one should check if the loglevel is actually enabled, or otherwise skip the associate String creation and manipulation

Label Label Label

Bad Example
log.debug("log something {} and {}", param1, param2);
Good Example
if (log.isDebugEnabled()) {
log.debug("log something" + param1 + " and " + param2 + "concat strings");
}

Logger Is Not Static Final

Description: In most cases, the Logger reference can be declared as static and final

Label Label Label

Bad Example
public class Alpha{
Logger log = Logger.getLogger(Alpha.class.getName());
}
Good Example
public class Alpha{
static final Logger log = Logger.getLogger(Alpha.class.getName());
}

More Than One Logger

Description: Normally only one logger is used in each class

Label Label Label

Bad Example
public class Alpha {
Logger log1 = Logger.getLogger(Alpha.class.getName());
Logger log2= Logger.getLogger(Alpha.class.getName());
}
Good Example
public class Alpha {
Logger log = Logger.getLogger(Alpha.class.getName());
}

System Println

Description: References to System.(out|err).print are usually intended for debugging purposes. Use a logger instead

Label Label Label

Bad Example
class Alpha{
Logger log = Logger.getLogger(Alpha.class.getName());
public void testAlpha () {
System.out.println("This test");
}
}
Good Example
class Alpha{
Logger log = Logger.getLogger(Alpha.class.getName());
public void testAlpha () {
log.fine("This test");
}
}

Missing Serial Version UID

Description: Serializable classes should provide a serialVersionUID field

Label Label Label

Bad Example
public class Alpha implements java.io.Serializable {
String test;
//doSomething
}
Good Example
public class Alpha implements java.io.Serializable {
String test;
public static final long serialVersionUID = 4916737;
}

Avoid Dollar Signs

Description: Avoid using dollar signs in variable/method/class/interface names

Label Label Label

Bad Example
public class Alp$ha {
}
Good Example
public class Alpha {
}

Avoid Field Name Matching Method Name

Description: It can be confusing to have a field name with the same name as a method

Label Label Label

Bad Example
public class Alpha {
Object beta;
void beta() {
}
}
Good Example
public class Alpha {
Object beta;
void theta() {
}
}

Avoid Field Name Matching Type Name

Description: It is somewhat confusing to have a field name matching the declaring class name

Label Label Label

Bad Example
public class Alpha extends Beta {
int alpha;
}
Good Example
public class Alpha extends Beta {
int theta;
}

Boolean Get Method Name

Description: Methods that return boolean results should be named as predicate statements to denote this. I.e, ‘isReady()’, ‘hasValues()’, ‘canCommit()’, ‘willFail()’, etc. Avoid the use of the ‘get’ prefix for these methods

Label Label Label

Bad Example
public boolean getAlpha();
Good Example
public boolean isAlpha();

Class Naming Conventions

Description: Configurable naming conventions for type declarations

Label Label Label

Bad Example
public class Étudiant {}
Good Example
public class AlphaBeta {}

Generics Naming

Description: Names for references to generic values should be limited to a single uppercase letter

Label Label Label

Bad Example
public interface GenericDao<e extends BaseModel, K extends Serializable> {
}
Good Example
public interface GenericDao<E extends BaseModel, K extends Serializable> {
}

Method Naming Conventions

Description: Configurable naming conventions for method declarations

Label Label Label


Method With Same Name As Enclosing Class

Description: Non-constructor methods should not have the same name as the enclosing class

Label Label Label

Bad Example
public class AlphaT {
public void AlphaT() {}
}
Good Example
public class AlphaT {
public AlphaT() {}
}

No Package

Description: A class, interface, enum or annotation does not have a package definition

Label Label Label


Package Case

Description: The package definition contains uppercase characters

Label Label Label

Bad Example
package com.MyAlpha;
Good Example
package com.myalpha;

Short Class Name

Description: Short Classnames with fewer than e.g. five characters are not recommended

Label Label Label

Bad Example
public class Alp {
}
Good Example
public class Alpha {
}

Short Method Name

Description: Method names that are very short are not helpful to the reader

Label Label Label

Bad Example
public class Alpha {
public void a( int i ) {
}
}
Good Example
public class Alpha {
public void beta( int i ) {
}
}

Suspicious Constant Field Name

Description: Field names using all uppercase characters - Sun’s Java naming conventions indicating constants - should be declared as final

Label Label Label

Bad Example
public class Alpha {
double PI = 3.16;
}
Good Example
public class Alpha {
final double PI = 3.16;
}

Suspicious Equals Method Name

Description: The method name and parameter number are suspiciously close to equals(Object), which can denote an intention to override the equals(Object) method

Label Label Label

Bad Example
public class Alpha {
public int equals(Object a) {
//doSomething
}
}
Good Example
public class Alpha {
public boolean equals(Object a) {
//doSomething
}
}

Suspicious Hashcode Method Name

Description: The method name and return type are suspiciously close to hashCode(), which may denote an intention to override the hashCode() method

Label Label Label

Bad Example
public class Alpha {
public int hashcode() {
}
}
Good Example
public class Alpha {
public int newname() {
}
}

Variable Naming Conventions

Description: Final variables should be fully capitalized and non-final variables should not include underscores

Label Label Label

Bad Example
public class Alpha {
public static final int my_alp = 0;
}
Good Example
public class Alpha {
public static final int MY_ALP = 0;
}

Add Empty String

Description: The conversion of literals to strings by concatenating them with empty strings is inefficient. It is much better to use one of the type-specific toString() methods instead

Label Label Label

Bad Example
String a = "" + 456; 
Good Example
String a = Integer.toString(456);

Avoid Array Loops

Description: Instead of manually copying data between two arrays, use the efficient Arrays.copyOf or System.arraycopy method instead

Label Label Label

Bad Example
public class Alpha {
public void beta() {
int[] x = new int[5];
int[]y = new int[5];
for (int i = 0; i < 5 ; i++) {
y[i] = x[i];
}
int[] z = new int[5];
for (int i = 0 ; i < 5 ; i++) {
y[i] = x[z[i]];
}
}
}

Redundant Field Initializer

Description: Java will initialize fields with known default values so any explicit initialization of those same defaults is redundant and results in a larger class file (approximately three additional bytecode instructions per field)

Label Label Label

Bad Example
public class Alpha {
boolean a = false;
}

Unnecessary Wrapper Object Creation

Description: Most wrapper classes provide static conversion methods that avoid the need to create intermediate objects just to create the primitive forms. Using these avoids the cost of creating objects that also need to be garbage-collected later

Label Label Label

Bad Example
public int convert(String a) {
int x, x2;

x = Integer.valueOf(a).intValue();

x2 = Integer.valueOf(x).intValue();

return x2;
}
Good Example
public int convert(String a) {
int x, x2;
x = Integer.parseInt(a);
x2 = x;

return x2;
}

Use Array List Instead Of Vector

Description: ArrayList is a much better Collection implementation than Vector if thread-safe operation is not required

Label Label Label

Bad Example
public class Alpha extends Beta {
public void testAlpha() {
Collection b = new Vector();
}
}
Good Example
public class Alpha extends Beta {
public void testAlpha() {
Collection b = new ArrayList();
}
}

Use Arrays As List

Description: "The java.util.Arrays class has a ""asList"" method that should be used when you want to create a new List from an array of objects. It is faster than executing a loop to copy all the elements of the array one by one"

Label Label Label

Bad Example
public class Alpha {
public void beta(Integer[] ints) {
List<Integer> l = new ArrayList<>(50);
for (int i = 0 ; i < 50; i++) {
l.add(ints[i]);
}
}
}
Good Example
public class Alpha {
public void beta(Integer[] ints) {
List<Integer> l= new ArrayList<>(50);
for (int i = 0 ; i < 50; i++) {
l.add(a[i].toString());
}
}
}

Use String Buffer For String Appends

Description: The use of the ‘+=’ operator for appending strings causes the JVM to create and use an internal StringBuffer. If a non-trivial number of these concatenations are being used then the explicit use of a StringBuilder or threadsafe StringBuffer is recommended to avoid this

Label Label Label

Bad Example
public class Alpha {
void beta() {
String c;
c = "alpha";
c += " beta";
}
}
Good Example
public class Alpha {
void beta() {
String c;
StringBuilder c = new StringBuilder("alpha");
c.append(" beta");
}
}
</