Java Coding Conventions Rules
Many of the Java coding conventions can be found from in Java Language Specification from James Gosling, Bill Joy, Guy L. Steele Jr and Gilad Bracha. See JLANGSPEC .
Overview
Table A.4. Java Coding Conventions Overview
JAC_001: Do Not Make An Attribute Non final And static (Low)
This rule helps you to avoid non final static attributes.
WRONG
static ArrayList InterfaceListeners = new ArrayList();
RIGHT
static final ArrayList InterfaceListeners = new ArrayList();
Exception(s):
- Using an attribute that represents the instance in a singleton can not be made final. In this case this rule is not applicable.
- Is not applicable when the static instance is used in a lazy initialization mechanism.
JAC_002: Do Not Reference A static Member Through An Object Instance (High)
static members should be referenced through class names rather than through objects.
WRONG
class Foo1 {
void func() {
Foo2 obj = new Foo2();
int i = obj.CONSTANT;
obj.operation();
}
}
class Foo2 {
static final int CONSTANT = 10;
static void operation() {}
}
RIGHT
class Foo1 {
void func() {
int i = Foo2.CONSTANT;
Foo2.operation();
}
}
class Foo2 {
static final int CONSTANT = 10;
static void operation() {}
}
JAC_003: Do Not Make A File Longer Than 2000 Lines (Enforced)
According to the Sun coding conventions, files longer than 2000 lines are cumbersome and should be avoided.
JAC_004: Do Not Make A Line Longer Than 120 Characters (Normal)
According to Sun coding conventions, lines longer than 80 characters should be avoided, since they're not handled well by many terminals and tools.
JAC_005: Do Not Use Complex Variable Assignment (High)
This rule checks for the occurrence of multiple assignments and assignments to variables within the same expression. You should avoid using assignments that are too complex, since they decrease program readability.
WRONG
i *= j++;
k = j = 10;
l = j += 15;
i = j++ + 20;
i = (j = 25) + 30;
RIGHT
j++;
i *= j;
k = 10;
j = 10;
j += 15;
l = j;
j++;
i = j + 20;
j = 25;
i = j + 30;
JAC_006: Do Not Code Numerical Constants Directly (Low)
According to Sun Code Conventions, numerical constants (literals) should not be coded directly, except for -1, 0, and 1, which can appear in a for loop as counter values.
 | Tip
Add static final attributes for numeric constants. See also rule [JAN_005: Use A Correct Name For A Constant (Enforced)]. |
JAC_007: Do Not Place Multiple Statements On The Same Line (High)
According to Sun coding conventions, each line should contain at most one statement.
WRONG
if (someCondition) someMethod();
i++; j++;
RIGHT
if (someCondition) {
someMethod();
}
i++;
j++;
JAC_008: Parenthesize The Conditional Part Of A Ternary Conditional Expression (High)
According to Sun coding conventions, if an expression containing a binary operator appears before the ? in the ternary ?: operator, it should be parenthesized.
WRONG
RIGHT
return (x >= 0) ? x : -x;
JAC_009: Provide An Incremental In A for Statement (High)
This rule checks whether the third argument of a for statement is missing.
WRONG
for (Enumeration enum = getEnum(); enum.hasMoreElements();) {
Object o = enum.nextElement();
doSomeProc(o);
}
 | Tip
Either provide the incremental part of the for structure, or cast the for statement into a while statement. |
RIGHT
Enumeration enum = getEnum();
while (enum.hasMoreElements()) {
Object o = enum.nextElement();
doSomeProc(o);
}
JAC_010: Do Not Use A Demand Import (Enforced)
Demand import-declarations must be replaced by a list of single import-declarations that are actually imported into the compilation unit. In other words, import statements should not end with an asterisk.
WRONG
import java.util.*;
import be.vlaanderen.myproject.mypackage.*;
RIGHT
import java.util.Date;
import be.vlaanderen.myproject.mypackage.MyClass;
JAC_011: Provide A default case In A switch Statement (Enforced)
According to Sun coding conventions, every switch statement should include a default case.
 | Tip
Put an assertion in the default case if you expect the default case never to be called. |
JAC_012: Use The Abbreviated Assignment Operator When Possible (Normal)
Use the abbreviated assignment operator in order to write programs more rapidly. Also some compilers run faster when you do so.
WRONG
void bar() {
int i = 0;
i = i + 20;
i = 30 * i;
}
RIGHT
void bar() {
int i = 0;
i += 20;
i *= 30;
}
JAC_013: Do Not Make A Method Longer Then 60 Lines (Normal)
A method should not be longer than 1 page (60 lines). If a method is more than one page long, it can probably be split. A method should do only one thing.
JAC_014: Do Not Make A switch Statement With More Than 256 Cases (Normal)
switch statements should not have more than 256 cases.
JAC_015: Do Not Chain Multiple Methods (Normal)
Do not chain method calls. Exceptionally, a chain of 2 method calls can be used.
Take the following line of code:
ret = object.method1().method2().method3();
If the return value from one of the methods is null you would get a NullPointerException. But which one is it?
It's better to use:
ret1 = object.method1();
ret2 = ret1.mehthod2();
ret3 = ret2.method3();
 | Note
See also the "Law of Demeter" which is a design guideline for developing software, explaining that an object should assume as little as possible about the structure or propertie. |
JAC_016: Use A Single return Statement (Normal)
Try to only use 1 return statement in a method (one point of entry and exit). This makes it easier to read and debug the code. Using a single return also allows for post-conditions to be checked.
WRONG
public int indexOf(Object something) {
for (int i = 0; i < collection.size(); i++) {
if (collection.get(i).equals(something)) {
return i;
}
}
return -1;
}
RIGHT
public int indexOf(Object something) {
int index = -1;
for (int i = 0; (index == -1) && (i < collection.size()); i++) {
if (collection.get(i).equals(something)) {
index = i;
}
}
return index;
}
JAC_017: Do Not Duplicate An import Declaration (Enforced)
There should be at most one import declaration that imports a particular class/package.
WRONG
package be.vlaanderen.myproject.mypackage.subpackage;
import java.io.IOException;
import java.io.Reader;
import java.sql.Time;
import java.sql.Time;
public class Foo {
}
RIGHT
package be.vlaanderen.myproject.mypackage.subpackage;
import java.io.IOException;
import java.io.Reader;
import java.sql.Time;
public class Foo {
}
JAC_018: Do Not Import A Class Of The Package To Which The Source File Belongs (Enforced)
No classes or interfaces need to be imported from the package that the source code file belongs to. Everything in that package is available without explicit import statements.
WRONG
package be.vlaanderen.myproject.mypackage;
import be.vlaanderen.myproject.mypackage.OtherFoo;
public class Foo {
public void setOtherFoo(OtherFoo other) {
}
}
RIGHT
package be.vlaanderen.myproject.mypackage;
public class Foo {
public void setOtherFoo(OtherFoo other) {
}
}
JAC_019: Do Not Import A Class From The Package java.lang (Enforced)
Explicit import of classes from the package java.lang should not be performed.
WRONG
package be.vlaanderen.myproject.mypackage.subpackage;
import java.lang.String;
public class Foo {
public void setName(String str) {
}
}
RIGHT
package be.vlaanderen.myproject.mypackage.subpackage;
public class Foo {
public void setName(String str) {
}
}
JAC_020: Do Not Use An Equality Operation With A boolean Literal Argument (Enforced)
Avoid performing equality operations on boolean operands. You should not use true and false literals in conditional clauses. By following this rule, you save some byte code instructions in the generated code and improve performance. In most situations, you also improve readability of the program.
WRONG
boolean isLoaded = true;
if (isLoaded == true) {
}
RIGHT
boolean isLoaded = true;
if (isLoaded) {
}
JAC_021: Do Not Import A Class Without Using It (Enforced)
This rule checks only those classes and interfaces that are explicitly imported by their names. It is not legal to import a class or an interface and never use it. If unused class and interface imports are omitted, the amount of meaningless source code is reduced - thus the amount of code to be understood by a reader is minimized.
WRONG
import java.awt.Button;
import java.util.Dictionary;
import java.util.Hashtable;
import java.util.Stack;
import java.util.Vector;
public class Foo {
Dictionary dict;
void func(Vector vec) {
Hashtable ht;
}
}
RIGHT
import java.util.Dictionary;
import java.util.Hashtable;
import java.util.Vector;
public class Foo {
Dictionary dict;
void func(Vector vec) {
Hashtable ht;
}
}
JAC_022: Do Not Unnecessary Parenthesize A return Statement (Normal)
According to Sun coding conventions, a return statement with a value should not use parentheses unless they make the return value more obvious in some way.
WRONG
RIGHT
JAC_023: Do Not Declare A private Class Member Without Using It (Enforced)
An unused class member might indicate a logical flaw in the program. The class declaration has to be reconsidered in order to determine the need of the unused member(s).
 | Tip
Examine the program. If the given member is really unnecessary, remove it (or at least comment it out). |
JAC_024: Do Not Use Unnecessary Modifiers For An Interface Method (Low)
All interface methods are implicitly public and abstract. However, the language permits the use of these modifiers with interface methods. Such use is not recommended (See JLANGSPEC - section 9.4). Some day, this may be disallowed by Java. It is far less painful to clean up your code before this happens.
WRONG
interface Foo {
public abstract void operation();
}
RIGHT
interface Foo {
void operation();
}
JAC_025: Do Not Use Unnecessary Modifiers For An Interface Field (Low)
All interface fields are implicitly public, static and final. However, the language permits the use of these modifiers with interface fields. Such use is not recommended (See JLANGSPEC - section 9.3). Some day, this may be disallowed by Java. It is far less painful to clean up your code before this happens.
WRONG
interface Foo {
public final static int ATTR = 10;
}
RIGHT
interface Foo {
int ATTR = 10;
}
 | Note
If the above interface Foo is used to collect all the constant then access the constant variable ATTR through the interface and not by implementing the interface ! To avoid this design misuse just place all your constants in a class. |
JAC_026: Do Not Use Unnecessary Modifiers For An Interface (High)
The modifier abstract is considered obsolete and should not be used.
WRONG
abstract interface Foo {
}
RIGHT
JAC_027: Do Not Declare A Local Variable Without Using It (Enforced)
Local variables should be used.
WRONG
int bar(int param) {
int unused_var;
return 2 * param;
}
JAC_028: Do Not Do An Unnecessary Typecast (High)
Checks for the use of type casts that are not necessary, including redundant upcasts.
WRONG
public class FooA {
}
public class FooB extends FooA {
public void bar(FooB b) {
FooA a = (FooA) b; }
}
RIGHT
public class FooA {
}
public class FooB extends FooA {
public void bar(FooB b) {
FooA a = b;
}
}
 | Tip
- Delete redundant upcasts to improve readability.
- In THINKING from Bruce Eckel, chapter 3 Controlling Program Flow has a section on casting operators and chapter 7 Polymorphism writes about up casting.
|
JAC_029: Do Not Do An Unnecessary instanceof Evaluation (High)
The instanceof expression checks that the runtime type of the left-hand side expression is the same as the one specified on the right-hand side. However, if the static type of the left-hand side is already the same as the right-hand side, then the use of the instanceof expression is questionable.
WRONG
public class FooA {
public FooA() {
}
public void bar() {}
}
class FooB extends FooA {
public void barbar(FooB b) {
if (b instanceof FooA) { b.bar();
}
}
}
RIGHT
public class FooA {
public FooA() {
}
public void bar() {}
}
class FooB extends FooA {
public void barbar(FooB b) {
b.bar();
}
}
JAC_030: Do Not Hide An Inherited Attribute (High)
This rule detects when attributes declared in child classes hide inherited attributes.
WRONG
class Foo {
int attrib = 10;
}
class Foo1 extends Foo {
int attrib = 0;
}
RIGHT
class Foo {
int attrib = 10;
}
class Foo1 extends Foo {
int foo1Attrib = 0;
}
JAC_031: Do Not Hide An Inherited static Method (High)
This rule detects when inherited static operations are hidden by child classes.
WRONG
class Foo1 extends Foo {
void oper1() {
}
static void oper2() {
}
}
class Foo {
static void oper1() {
}
static void oper2() {
}
}
RIGHT
class Foo1 extends Foo {
static void anOper2() {
}
void anOper1() {
}
}
class Foo {
static void oper1() {
}
static void oper2() {
}
}
JAC_032: Do Not Declare Overloaded Constructors Or Methods With Different Visibility Modifiers (High)
Overload resolution only considers constructors and methods visible at the point of the call. But when all the constructors and methods are considered, there may be more matches.
Imagine that FooB is in a different package than FooA. Then the allocation of FooB violates this rule, because the second and third constructor (FooA(char param) and FooA(short param)) are not visible at the point of the allocation because the modifier for both constructors is not public but package local.
WRONG
public class FooA {
public FooA(int param) {
}
FooA(char param) {
}
FooA(short param) {
}
}
RIGHT
public class FooA {
public FooA(int param) {
}
public FooA(char param) {
}
public FooA(short param) {
}
}
JAC_033: Do Not Override A Non abstract Method With An abstract Method (High)
Checks for the overriding of non-abstract methods by abstract methods in a subclass.
WRONG
public class Animal {
void func() {
}
}
abstract class Elephant extends Animal {
abstract void func();
}
 | Tip
If this is just a coincidence of names, then just rename your method. If not, either make the given method abstract in the ancestor or non abstract in the descendant. |
RIGHT
public class Animal {
void func() {
}
}
abstract class Elephant extends Animal {
abstract void extFunc();
}
JAC_034: Do Not Override A private Method (High)
A subclass should not contain a method with the same name and signature as in a super class if these methods are declared to be private.
WRONG
public class Animal {
private void func() {
}
}
class Elephant extends Animal {
private void func() {
}
}
RIGHT
public class Animal {
private void func() {
}
}
class Elephant extends Animal {
private void extFunc() {
}
}
JAC_035: Do Not Overload A Super Class Method Without Overriding It (High)
A super class method may not be overloaded within a subclass unless all overloaded methods in the super class are also overridden in the subclass. It is very unusual for a subclass to be overloading methods in its super class without also overriding the methods it is overloading. More frequently this happens due to inconsistent changes between the super class and subclass, i.e. the intention of the user is to override the method in the super class, but due to an error, the subclass method ends up overloading the super class method.
WRONG
class FooB {
public void bar(int i) {
}
public void bar(Object o) {
}
}
public class FooA extends FooB {
public void bar(char c) {
}
public void bar(Object o) {
}
}
RIGHT
class FooB {
public void bar(int i) {
}
public void bar(Object o) {
}
}
public class FooA extends FooB {
public void bar(char c) {
}
public void bar(int i) {
}
public void bar(Object o) {
}
}
JAC_036: Do Not Use A Non final static Attribute For Initialization (High)
Non final static attributes should not be used in initializations of attributes.
WRONG
public class FooA {
static int state = 15;
static int attr1 = state;
static int attr2 = FooA.state;
static int attr3 = FooB.state;
}
public class FooB {
static int state = 25;
}
RIGHT
public class FooA {
static final int INITIAL_STATE = 15;
static int state = 15;
static int attr1 = INITIAL_STATE;
static int attr2 = FooA.state;
static int attr3 = FooB.state;
}
public class FooB {
static int state = 25;
}
JAC_037: Do Not Use Constants With Unnecessary Equal Values (High)
This rule catches constants with equal values. The presence of different constants with equal values can cause bugs if these constants have equal meaning.
WRONG
final static int SUNDAY = 0;
final static int MONDAY = 1;
final static int TUESDAY = 2;
final static int WEDNESDAY = 3;
final static int THURSDAY = 4;
final static int FRIDAY = 5;
final static int SATURDAY = 0;
String getDayName(int day) {
if (day == SUNDAY) {
return "Sunday";
} else if (day == SATURDAY) {
return "Saturday";
}
}
[Note] Note
Enumerations are finally supported in JDK 1.5, making the above example a lot simpler and eliminating the mentioned problem!
JAC_038: Provide At Least One Statement In A catch Block (Normal)
catch blocks should not be empty. Programmers frequently forget to process negative outcomes of a program and tend to focus more on the positive outcomes. There are situations where the programmer can prove that the exception will never be thrown, but still has to include a catch clause to satisfy the Java language rules.
 | Tip
When an empty catch block is specified it usually means that the exception being catched is not expected. In this case you should use an assertion to make sure that the exception is not thrown or throw a java.lang.Error or another runtime exception. |
WRONG
try {
monitor.wait();
} catch (InterruptedException e) {
}
RIGHT
try {
monitor.wait();
} catch (InterruptedException e) {
logger.log(Level.WARNING, "Program Interrupted", e);
throw new Error("Unexpected exception");
}
JAC_039: Do Not Catch java.lang.Exception Or java.lang.Throwable (Normal)
catch clauses must use exception types that are as specific as possible for the exception that may be thrown from the corresponding try block. By catching all exceptions a developer might also catch for example a java.lang.OutOfMemoryException and interpret it in the wrong way (see example below). Following this rule catches programmer tardiness in fully enumerating the exception situations and properly handling them. As a rules developers should only catch what is thrown.
Exceptions to this rule are allowed if a method in a third party library throws a java.lang.Exception or java.lang.Throwable exception. In this case catching the general exception is allowed.
WRONG
try {
file = new FileInputStream("myfile");
} catch (Throwable e) {
logger.log(Level.WARNING, "File myfile not found");
}
RIGHT
try {
file = new FileInputStream("myfile");
} catch (IOException e) {
logger.log(Level.WARNING, "File myfile not found");
} finally {
}
JAC_040: Do Not Give An Attribute A public Or Package Local Modifier (Enforced)
Declare the attributes either private or protected and provide operations to access or change them. Also referred to as full encapsulation.
There might be one exception when some class is used just as struct in C language: it just holds some values, and thus has no methods.
WRONG
public class Foo {
int attr1;
public int attr2;
protected int attr3
}
RIGHT
public class Foo {
private int attr1;
private int attr2;
int getAttr1() {
return attr1;
}
public int getAttr2() {
return attr2;
}
protected int getAttr3() {
return attr3;
}
}
JAC_041: Provide At Least One Statement In A Statement Body (Enforced)
As far as possible, avoid using statements with empty bodies.
WRONG
StringTokenizer st = new StringTokenizer(class1.getName(), ".", true);
String s;
for (s = ""; st.countTokens() > 2; s = s + st.nextToken());
 | Tip Provide a statement body or change the logic of the program (for example, use a while statement instead of a for statement). |
RIGHT
StringTokenizer st = new StringTokenizer(class1.getName(), ".", true);
String s = "";
while (st.countTokens() > 2) {
s += st.nextToken();
}
JAC_042: Do Not Compare Floating Point Types (Low)
Avoid testing floating point numbers for equality. Floating-point numbers that should be equal are not always equal due to rounding problems.
WRONG
void bar(double d) {
if (d != 15.0) {
for (double f = 0.0; f < d; f += 1.0) {
}
}
}
 | Tip Replace direct comparison with estimation of absolute value of difference. |
RIGHT
void bar(double d) {
if (Math.abs(d - 15.0) < Double.MIN_VALUE * 2) {
for (double f = 0.0; d - f > DIFF; f += 1.0) {
}
}
}
JAC_043: Enclose A Statement Body In A Loop Or Condition Block (Enforced)
The statement of a loop should always be a block. The then and else parts of if-statements should always be blocks. This makes it easier to add statements without accidentally introducing bugs due to forgetting to add braces.
WRONG
if (st == null)
st = "";
while (st.countTokens() > 2)
s += st.nextToken();
RIGHT
if (st != null) {
st = "";
}
while (st.countTokens() > 2) {
s += st.nextToken();
}
JAC_044: Explicitly Initialize A Local Variable (High)
Explicitly initialize all method variables. The only reason not to initialize a variable where it's declared is if the initial value depends on some computation occurring first.
WRONG
RIGHT
void bar() {
int var = 0;
}
JAC_045: Do Not Unnecessary Override The finalize Method (High)
As mentioned in JLANGSPEC, calling super.finalize() from finalize() is a good programming practice, even if the base class doesn't define the finalize method. This makes class implementations less dependent on each other.
However as also mentioned in EFFECJ finalizers are unpredictable, often dangerous and generally unnecessary and as a rule of thumb finalizers should be avoided.
WRONG
public class Foo {
public void finalize() {
super.finalize();
}
}
RIGHT
public class Foo {
/* Remove the finalize method
public void finalize() {
super.finalize();
}
*/
}
JAC_046: Parenthesize Mixed Logical Operators (High)
An expression containing multiple logical operators together should be parenthesized properly.
WRONG
void bar() {
boolean a = false
boolean b = true;
boolean c = false;
if (a || b && c) {
}
}
 | Tip Use parentheses to clarify complex logical expressions for the reader. Also when using boolean variables use the naming conventions is or has as a prefix. For example: isLoading, hasFinished |
RIGHT
void bar() {
boolean a = false;
boolean b = true;
boolean c = false;
if (a || (b && c)) {
}
}
JAC_047: Do Not Assign Values In A Conditional Expression (High)
Use of assignments within conditions makes the source code hard to understand.
WRONG
if ((dir = new File(targetDir)).exists()) {
}
RIGHT
File dir = new File(targetDir);
if (dir.exists()) {
}
JAC_048: Provide A break Statement Or Comment For A case Statement (Normal)
According to Sun coding conventions, every time a case falls through (doesn't include a break statement), a comment should be added where the break statement would normally be. The break in the default case is redundant, but it prevents a fall-through error if later another case is added.
WRONG
switch (c) {
case Constants.NEWLINE:
result += Constants.NEWLINE;
break;
case Constants.RETURN:
result += Constants.RETURN;
break;
case Constants.ESCAPE:
someFlag = true;
case Constants.QUOTE:
result += c;
break;
}
 | Tip Add the comment '// falls through' where the break statement would normally be. |
RIGHT
switch (c) {
case Constants.NEWLINE:
result += Constants.NEWLINE;
break;
case Constants.RETURN:
result += Constants.RETURN;
break;
case Constants.ESCAPE:
someFlag = true;
case Constants.QUOTE:
result += c;
break;
default: }
JAC_049: Use equals To Compare Strings (Enforced)
The == operator used on strings checks whether two string objects are two identical objects. However, in most situations, you simply want to check for two strings that have the same value. In this case, the method equals should be used.
WRONG
void func(String str1, String str2) {
if (str1 == str2) {
}
}
 | Tip Replace the '==' operator with the equals method. |
RIGHT
void func(String str1, String str2) {
if (str1.equals(str2)) {
}
}
JAC_050: Use L Instead Of l At The End Of A long Constant (Enforced)
It is difficult to distinguish the lower case letter l from the digit 1. When the letter l is used as the long modifier at the end of an integer constant, it can be confused with digits. In this case, it is better to use an uppercase L.
WRONG
void bar() {
long var = 0x0001111l;
}
RIGHT
void bar() {
long var = 0x0001111L;
}
JAC_051: Do Not Use The synchronized Modifier For A Method (Normal)
The synchronized modifier on methods can sometimes cause confusion during maintenance as well as during debugging. This rule therefore recommends using synchronized statements as replacements instead.
WRONG
public class Foo {
public synchronized void bar() {
}
}
 | Tip Use synchronized statements instead of synchronized methods. |
RIGHT
public class Foo {
public void bar() {
synchronized(this) {
}
}
}
[Note] Note
See rule JAC_061: Do Not Return From Inside A try Block (High).
JAC_052: Declare Variables Outside A Loop When Possible (Normal)
This rule recommends declaring local variables outside the loops. The reason: as a rule, declaring variables inside the loop is less efficient.
WRONG
for (int i = 0; i < 100; i++) {
int var1 = 0;
}
while (true) {
int var2 = 0;
}
do {
int var3 = 0;
} while (true);
 | Tip Move variable declarations out of the loop |
RIGHT
int var1;
for (int i = 0; i < 100; i++) {
var1 = 0;
}
int var2;
while (true) {
var2 = 0;
}
int var3;
do {
var3 = 0;
} while (true);
JAC_053: Do Not Append To A String Within A Loop (High)
Operations on the class String (in package java.lang) are not very efficient when compared to similar operations on StringBuffer (in package java.lang). Therefore, whenever possible, you should replace uses of String operations by StringBuffer operations. This rule checks for obvious misuse of String operations ? namely if a String object is appended to within a loop.
Significant performance enhancements can be obtained by replacing String operations with StringBuffer operations.
WRONG
public class Foo {
public String bar() {
String var = "var";
for (int i = 0; i < 10; i++) {
var += (" " + i);
}
return var;
}
}
 | Tip Use StringBuffer class instead of String |
RIGHT
public class Foo {
public String bar() {
StringBuffer var = new StringBuffer(23);
var.append("var");
for (int i = 0; i < 10; i++) {
var.append(" " + i);
}
return var.toString();
}
}
JAC_054: Do Not Make Complex Calculations Inside A Loop When Possible (Low)
Avoid using complex expressions as repeat conditions within loops. By following this rule, you move repeated calculations within loops ahead of the loop where only a single calculation needs to be made.
WRONG
void bar() {
for (int i = 0; i < vector.size(); i++) {
}
}
 | Tip Assign the expression to a variable before the loop and use that variable instead. |
RIGHT
void bar() {
int size = vector.size();
for (int i = 0; i < size; i++) {
}
}
JAC_055: Provide At Least One Statement In A try Block (Enforced)
Empty try blocks should be removed because they bring no added value to your code.
WRONG
try {
} catch (SQLException e) {
logger.log(Level.WARNING, "SQL Problem", e);
}
JAC_056: Provide At Least One Statement In A finally Block (Enforced)
An empty finally block can be removed from the try/catch block.
WRONG
try {
name = rs.getString(1);
} catch (SQLException e) {
logger.log(Level.WARNING, "SQL Problem", e);
} finally {
}
RIGHT
try {
name = rs.getString(1);
} catch (SQLException e) {
logger.log(Level.WARNING, "SQL Problem", e);
}
JAC_057: Do Not Unnecessary Jumble Loop Incrementors (High)
Avoid and correct jumbled loop incrementors because this is either a mistake or it makes the code unclear to read.
WRONG
public void bar() {
for (int i = 0; i < 10; i++) {
for (int j = 0; j < 10; i++) {
logger.info("i = " + i + ", j =" +j);
}
}
}
RIGHT
public void bar() {
for (int i = 0; i < 10; i++) {
for (int j = 0; j < 10; j++) {
logger.info("i = " + i + ", j =" +j);
}
}
}
JAC_058: Do Not Unnecessary Convert A String (High)
Avoid unnecessary String variables when converting a primitive to a String.
WRONG
public String bar(int x) {
String foo = new Integer(x).toString();
return foo;
}
RIGHT
public String bar(int x) {
return Integer.toString(x);
}
JAC_059: Override The equals And hashCode Methods Together (Enforced)
Override both public boolean Object.equals(Object other), and public int Object.hashCode(), or override neither. Even if you are inheriting a hashCode() from a parent class, consider implementing hashCode and explicitly delegating to your super class.
WRONG
public class Foo {
public boolean equals(Object o) {
}
}
RIGHT
public class Foo {
public boolean equals(Object o) {
}
public int hashCode() {
}
}
JAC_060: Do Not Use Double Checked Locking With Lazy Initialization (Enforced)
Lazy initialization code could return a NullPointerException when the method is used in a multi-threaded application, however the double checked lazy initialization does not work for all cases (See Effective Java).
WRONG
public class Foo {
private static Resource resource = null;
public static Resource getResource() {
if (resource == null) {
synchronized (Foo.class) {
if (resource == null) {
resource = new Resource();
}
}
}
return resource;
}
}
 | Tip Read Item 48: Synchronize access to shared mutable data in EFFECJ . |
JAC_061: Do Not Return From Inside A try Block (High)
Code leaves the try block when it finishes normally, when an exception is thrown or a return, break or continue statement is executed. When a finally block exists, it will always be executed. This means that a return in a try block is not guaranteed to be the normal flow of the code! Putting a return statement in a try block might lead a developer to think that the finally block will not be executed.
[Note] Note
See also rule JAC_016: Use A Single return Statement (Normal).
JAC_062: Do Not Return From Inside A finally Block (High)
Feedback
Avoid returning from a finally block - this can discard exceptions.
WRONG
public void bar() {
try {
throw new JMSException("My Exception");
} catch (JMSException e) {
logger.log(Level.WARNING, "JMS Problem", e);
throw e;
} finally {
return;
}
}
RIGHT
public void bar() {
try {
throw new JMSException("My JMS Exception");
} catch (JMSException e) {
flag = "NOK";
logger.log(Level.WARNING, "JMS Problem", e);
throw e;
} finally {
}
}
JAC_063: Do Not Use A try Block Inside A Loop When Possible (Normal)
An application might slow down when placing a try/catch block in a loop.
WRONG
public void bar() {
int balance = 0;
for (int i = 0; i < account.length; i++) {
try {
balance = account[i].getValue();
account[i].setValue(balance * 1.2);
} catch (AccountValueNotValidException e) {
logger.log(Level.WARNING, "Account value not valid", e);
}
}
}
RIGHT
public void bar() {
int balance = 0;
try {
for (int i = 0; i < account.length; i++) {
balance = account[i].getValue();
account[i].setValue(balance * 1.2);
}
} catch (AccountValueNotValidException e) {
logger.log(Level.WARNING, "Account value not valid", e);
}
}
JAC_064: Do Not Use An Exception For Control Flow (High)
Using exceptions for flow control is just not a good idea. The example you can see below is a classic for people starting with the Java language.
WRONG
public void bar(int numbers[]) {
int i = 0;
try {
while (true) {
logger.info("number =" + numbers[i++]);
}
} catch (ArrayIndexOutOfBoundsException e) {
}
}
RIGHT
public void bar(int numbers[]) {
for (int i = 0; i < numbers.length; i++) {
logger.info("number =" + numbers[i]);
}
}
JAC_065: Do Not Unnecessary Use The System.out.print or System.err.print Methods (High)
The System.out.print and System.err.print methods are often mis-used as a simple way to debug or log your application. Either use Logging API or centralize these print methods in a debug class.
WRONG
public void bar() {
try {
System.out.println("I got here");
} catch (JMSException e) {
System.out.println("exception occurred");
e.printStackTrace();
} finally {
System.out.println("cleaning up");
}
}
RIGHT
public void bar() {
logger.entering("Foo", "foo");
try {
} catch (JMSException e) {
logger.log(Level.WARNING, "JMS Problem", e);
} finally {
logger.info("cleaning-up");
}
logger.existing("Foo", "foo");
}
JAC_066: Do Not Return In A Method With A Return Type of void (High)
Avoid unnecessary return statements, just remove this statement.
WRONG
public void bar() {
return;
}
RIGHT
JAC_067: Do Not Reassign A Parameter (Enforced)
Avoid reassigning values to parameters, use a temporary local variable instead.
WRONG
public void foo(String bar) {
bar = "Hello World";
}
RIGHT
public void foo(String bar) {
String tmp = "Hello World";
}
JAC_068: Close A Connection Inside A finally Block (Enforced)
Ensure that a connection object is always closed within the finally block.
WRONG
public void bar() {
ServerSocket serverSocket = new ServerSocket(0);
try {
Socket mySocket = serverSocket.accept();
mySocket.close();
} catch (IOException e) {
logger.log(Level.WARNING, "IO Problem", e);
}
}
RIGHT
public void bar() {
ServerSocket serverSocket = new ServerSocket(0);
Socket mySocket = null;
try {
mySocket = serverSocket.accept();
} catch (IOException e) {
logger.log(Level.WARNING, "IO Problem", e);
} finally {
closeConnection(mySocket);
}
}
 | Tip Use a helper method to close the connection, this makes the finally block small and readable. |
JAC_069: Do Not Declare A Method That Throws java.lang.Exception or java.lang.Throwable (Normal)
Feedback
A method must not throw java.lang.Exception or java.lang.Throwable because of the unclarity. Use either a class derived from java.lang.RuntimeException or a checked exception with a descriptive name. This rule is linked to rule JAC_039: Do Not Catch java.lang.Exception Or java.lang.Throwable (Normal).
WRONG
public void bar() throws Exception {
}
RIGHT
public void bar() throws BarException {
}
JAC_070: Do Not Use An instanceof Statement To Check An Exception (High)
Feedback
Do not check exceptions with instanceof, instead catch the specific exceptions.
WRONG
SimpleDateFormat sdf = new SimpleDateFormat("dd.MM.yyyy");
try {
returnString = sdf.format(value);
} catch (Exception e) {
if (e instanceof NumberFormatException) {
NumberFormatException nfe = (NumberFormatException) e;
logger.log(Level.WARNING, "NumberFormat exception", nfe);
}
if (e instanceof IllegalArgumentException) {
IllegalArgumentException iae = (IllegalArgumentException) e;
logger.log(Level.WARNING, "Illegal argument", iae);
}
}
RIGHT
SimpleDateFormat sdf = new SimpleDateFormat("dd.MM.yyyy");
try {
returnString = sdf.format(value);
} catch (NumberFormatException e) {
logger.log(Level.WARNING, "NumberFormat exception", e);
} catch (IllegalArgumentException e) {
logger.log(Level.WARNING, "Illegal argument", e);
}
JAC_071: Do Not Catch A RuntimeException (High)
Don't catch runtime exceptions. Runtime exceptions are generally used to report bugs in code and should therefore never be caught.
WRONG
public void doSomething() {
try {
doSomethingElse(null);
} catch (NullPointerException e) {
}
}
private void doSomethingElse(String arg) {
arg.trim();
}
RIGHT
Don't catch the NullPointerException runtime exception in doSomething(), instead fix the bug.
JAC_072: Do Not Use printStackTrace (High)
Don't use printStackTrace to report exceptions. The printStackTrace method prints the stack trace to standard error (usually the console). Unless the console output is redirected to a file the stack trace will be lost once the console's screen buffer becomes full. A better alternative is to use a logger and log the exception with the appropriate logging level.
JAC_073: Package Declaration Is Required (Enforced)
All classes must have a package declaration. Classes that live in the null package cannot be imported. Many novice developers are not aware of this.
WRONG
RIGHT
package some.package;
public class MyClass {
}