Over a million developers have joined DZone.
Platinum Partner

Improve Java Software Code Quality

· Java Zone

The Java Zone is brought to you in partnership with ZeroTurnaround. Discover how you can skip the build and redeploy process by using JRebel by ZeroTurnaround.

Improve Code Quality with FindBugs

In this article I discuss a static analysis tool that finds defects in Java programs. Static analysis tools can find real bugs and real issues in your code. You can effectively incorporate static analysis into your software development process.


FindBugs is an open source static analysis tool that analyzes Java class files, looking for programming defects. The analysis engine reports nearly 300 different bug patterns. Each bug pattern is grouped into a category (e.g., correctness, bad practice, performance and internationalization), and each report of a bug pattern is assigned a priority, high, medium or low.

Let’s start with some of the bug categories that I find very interesting


The code seems to be clearly doing something the developer did not intend

Infinite recursive loop

public String resultFound() {
return this.resultFound();

Null Pointer Bugs

FindBug look for the statement that when execute will surely produce Null Pointer Exceptio. Some examples are

if (str != null || str.length > 0)

if (str == null || str.equals(""))

if (obj != null)
//code to be execute

The below code is a relatively simply bug. If the test null == elt evaluates to false, we are guaranteed to get a null pointer exception when we dereference obj by invoking the equals method on it.

while(it.hasNext()) {
Object elt = it.next();
if((null == obj && null == elt)
|| obj.equals(elt)) {


Redundant Check for Null

We usually do such mistake. A value is checked here to see whether it is null, but this value can't be null because it was previously dereferenced and if it were null a null pointer exception would have occurred at the earlier dereference.

if(screen instanceof BasicScreen) {
BasicScreen basicScreen = (BasicScreen) screen;
BusinessComponent businessComponent = basicScreen.getBusinessComponent();
if(basicScreen!=null) {
dataBean = (UnderwriterPriority)businessComponent.getDataBean();

Above Figure shows the NULL Check of basic screen at line 4 of value previously dereference at line3.

Method whose return value should not ignore

We all know string is immutable object. So ignoring the return value of the method would consider as bug.

String name = "Muhammad";
if (name.equals("MUHAMMAD"))

Suspicious equal() comparision

The method calls equals(Object) on two references of different class types with no common subclasses 

Integer accountTypeValue = dataBean.getAccount_type_code();
if (accountTypeValue != null && !"".equals(accountTypeValue))
result = (accountTypeValue).intValue();

According to the contract of equals(), objects of different classes should always compare as unequal; Therefore equal comparision in line 2 always return false.

Bad Practice

Violations of recommended and essential coding practice. Examples include hash code and equals problems, cloneable idiom, dropped exceptions, serializable problems, and misuse of finalize.

Hash equals mismatch

Class defines equals() and uses Object.hashCode(). The class overrides equals(Object), but does not override hashCode(), and inherits the implementation of hashCode() from java.lang.Object (which returns the identity hash code, an arbitrary value assigned to the object by the VM).  Therefore, the class is very likely to violate the invariant that equal objects must have equal hashcodes. 

Ignore serialVersionUID

Class implementing serializable interface but forget to declare an explicit serial version UID.

Ignore Exception return values

Noncompliant Code Example

The following calls to java.io.File methods are non compliant because the program does not check the return
value, and hence does not know whether the operation succeeded.

void do_operation() {
File directory, file;
// fetch directory
// do some operations on file and directory

Compliant Solution

A compliant solution provides error handling to recover from an unsuccessful operation. This can be as simple as throwing an exception

void do_operation() throws FileNotFoundException {
File directory, file;
// fetch directory
if (( !directory.isDirectory()) && ( !directory.mkdir()) ) {
// recover from error or throw an exception
throw new FileNotFoundException("Unable to create directory " + directory );
// do some operations on file and directory
if ( !file.delete()) {
// recover from error or throw an exception
throw new FileNotFoundException("Failed to delete file " + file );


Code that is confusing, anomalous, or written in a way that leads itself to errors. Examples include dead local stores, switch fall through, unconfirmed casts, and redundant null check of value known to be null.

instanceof will always return true

The instanceof test will always return true (unless the value being tested is null)

NodeList nodeList = root.getElementsByTagName("node");

int nodeListLength = nodeList.getLength();

for (int i = 0; i < nodeListLength; i++) {
Node node = nodeList.item(i);

if (node instanceof Node && node.getParentNode() == root) {
//do code

Class doesn't override equals in superclass

This class extends a class that defines an equals method and adds fields, but doesn't define an equals method itself. Thus, equality on instances of this class will ignore the identity of the subclass and the added fields.

Check for oddness that won't work for negative numbers

The code uses x % 2 == 1 to check to see if a value is odd, but this won't work for negative numbers (e.g., (-5) % 2 == -1). If this code is intending to check for oddness, consider using x & 1 == 1, or x % 2 != 0. 


When should such defects be fixed?

Since these defects doesn’t cause the program to significantly misbehave, therefore the question is should these types of defect be fixed? The main arguments to fix these defects is that they require some good resources that could be better applied elsewhere, and that there is a chance that the attempt to fix the defect will introduce another, more serious bug that does significantly impact the behavior of the application. The primary argument for fixing such defects is that it makes the code easier to understand and maintain, and less likely to break in the face of future modifications or uses.


Download the  latest version of FindBugs.

Visit the  blog.

Using the FindBugs Ant task.

Using the FindBugs Eclipse plugin.


 - See more at: http://muhammadkhojaye.blogspot.com/2010/06/find-java-bugs-with-findbugs.html 

The Java Zone is brought to you in partnership with ZeroTurnaround. Discover how you can skip the build and redeploy process by using JRebel by ZeroTurnaround.


{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}