Muhammad Khojaye is an experienced consultant who has worked on both large scale Agile development projects for top financial clients and public sector innovative research and development projects. In his spare time, Muhammad likes to work on independent open source programs. Muhammad is a DZone MVB and is not an employee of DZone and has posted 13 posts at DZone. You can read more from them at their website. View Full User Profile

Improve Java Software Code Quality

  • submit to reddit

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 =;
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 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: 

Published at DZone with permission of Muhammad Khojaye, author and DZone MVB.

(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)


Mladen Girazovski replied on Mon, 2009/06/08 - 2:39am

I'm not sure if always adding a serialVersionUID to a serialisable class is a best practise.

After all, the decision to serialise/desirialise between different versions of the class has to be made explicit and not implizit for all serialisable classes, since under normal circumstances this is not what you want and it will lead to undifined behaviour if the classes haven't been designed that way.

Muhammad Khojaye replied on Mon, 2009/06/08 - 12:09pm

What I think (apart from FindBug) is that if we do not worry about versioning for the class -- that is., if the serialized data will never store in a file or shared with some other revision of the same program, then adding @suppressWarnings to class would be appropriate. Otherwise, adding serial ID would perfectly fine.

Mike P(Okidoky) replied on Mon, 2009/06/08 - 1:22pm

One great way of improving readability is to replace the awful K&R indentation/brace style to Allman style. You'd be surprised how much quicker you can run your eyes through source code. Even more so for JavaFX source.

SOR Rezawi replied on Mon, 2009/06/08 - 11:58pm

This is a great article. I will recommend this to my newer resources. The code samples help me understand the content of the topic. Thanks, and Keep writing.

Andrew Yang replied on Tue, 2009/06/09 - 9:47am

I second the last paragraph.  Static analysis results tend to have results that can range from: false positives (where the bug report is just wrong) to low to high priority defects.  Some tools are noiser than others but most do a good job of pointing out issues that should be fixed.  It also can find those occasional killer bugs with good regularity.   However, in my experience at Code Integrity Solutions, the day-to-day bug reports fit in the "yeah, I should fix it but it's not important right now" category.  Not surprisingly, in any software development organization's bug database there are often a large number of similarly categorized defects.  You're going to have a few bugs that fit in the high priority range and a large number in the medium and low priority. The difference with static analysis though is that you are getting these bug reports as you are developing and so it is much more efficient to clean these out as you are developing than looking at a bug report and starting from scratch to debug it.  The natural tendency is to ignore the reports coming from the static analysis tool.  A good practice is to make sure everything is clean before checking into the main line (that means every defect, at minimum, should be looked at and categorized).

Tom Lo replied on Wed, 2009/06/10 - 2:09am

Nice article.  I agree with the vast majority of what you have said here.  Very similar to part of our induction handbook for grads, with one exception - your final parapraph.  We like to keep clean code all the time, especially with a mix of experience within the coding teams.  We follow the practice of not working on new code until all defects are fixed.  While this sounds like a big hurdle, it's like cleaning the dishes - If you wash up after every meal from day one, it's never a big task.

Walter Bogaardt replied on Wed, 2009/06/10 - 5:37pm

This is a good idea, but it seems predicated on you specifically run Findbugs on your code base, or add to ant task. It should be integrated into your build environment and looked. In fact if you want true enforcement you would use it to "break" your CI builds to enforce compliance. There is arguments to be made about being a maniac about following coding standards and allowing some level of non-compliant code in your applications.  


Muhammad Khojaye replied on Thu, 2009/06/11 - 5:17am in response to: Walter Bogaardt

I strongly adhere to the point that FindBug should be made a part of continuous integration. In fact should be introduced early as possible in the Development cycle. This will help in bug detection closer to the point of bug injection. By this a bug will be removed early in the SDLC at the point where it’s most cost and time effective to fix it and also limits its propagation to later phases where it’s more costly to detect as well as fix. As far as being a maniac about following coding standards is concerned, it’s very important to enforce them rigorously especially if the team is fresh and inexperienced. Adherence to coding standards and automated tool support like Find bug can work as a safety net, detecting well-known bug patterns mention here.

Muhammad Khojaye replied on Thu, 2009/06/11 - 5:18am in response to: Walter Bogaardt


sub online replied on Fri, 2009/06/26 - 3:12am

go for it.Play dumb. Don't play dumb. You know about that.Tiffany JewelleryHow do I say this? It's so hard to explain How do I say this? What do you mean? I'm feeling sorry for him. What do you mean?Have you seen that movie 'Friday the 13th'? It's so sick.links of londonLooking for trouble.Is it too late? Can we make it?I need it badly.links of londonAre you finished? Are you done with that!It's not my fault.How dare you stand me up.Leave it up to me.Don't you have a heart!

Ayo Bakare replied on Thu, 2009/07/30 - 7:37pm

How easy is it to find the bug? Free Macbook | Free iPhone 3GS

linksof london replied on Tue, 2009/08/25 - 1:49am

Static analysis results tend to links of london necklaces have results that can range from: false positives (where the bug report is just wrong) to low to high priority defects. Some tools are noiser than others but most do a good job of pointing out issues that should be fixed.links of london sweetie Other new names opening at St David’s 2 include movable telecoms providers Carphone Warehouse, O2 and Vodafone; footwear seller Clarks; gift trader Clinton Cards and coffee store Starbucks. The Cardiff links of london jewellery centre will be links london breech contain create supplies New Look and Slaters who will be fusion the impending vacancies we will be loyal to update the location. As presently as we find out about the links of london jewelry

Comment viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.