FindBugs
 
Docs and Info
Demo and data
Users and supporters
FindBugs blog
Fact sheet
Manual (en)
Manual (ja)
FAQ
Bug descriptions
Mailing lists
Documents and Publications
Links
 
Downloads
 
FindBugs Swag
 
Development
Reporting bugs
Contributing
Dev team
API [no frames]
Change log
SF project page
Browse source

FindBugs Bug Descriptions

This document lists the standard bug patterns reported by FindBugs version 1.3.4.

Summary

DescriptionCategory
AM: Creates an empty jar file entryBad practice
AM: Creates an empty zip file entryBad practice
BC: Equals method should not assume anything about the type of its argumentBad practice
BC: Random object created and used only onceBad practice
BIT: Check for sign of bitwise operationBad practice
CN: Class implements Cloneable but does not define or use clone methodBad practice
CN: clone method does not call super.clone()Bad practice
CN: Class defines clone() but doesn't implement CloneableBad practice
Co: Abstract class defines covariant compareTo() methodBad practice
Co: Covariant compareTo() method definedBad practice
DE: Method might drop exceptionBad practice
DE: Method might ignore exceptionBad practice
DP: Classloaders should only be created inside doPrivileged blockBad practice
DP: Method invoked that should be only be invoked inside a doPrivileged blockBad practice
Dm: Method invokes System.exit(...)Bad practice
Dm: Method invokes dangerous method runFinalizersOnExit Bad practice
ES: Comparison of String parameter using == or !=Bad practice
ES: Comparison of String objects using == or !=Bad practice
Eq: Abstract class defines covariant equals() methodBad practice
Eq: Class defines compareTo(...) and uses Object.equals()Bad practice
Eq: Covariant equals() method definedBad practice
FI: Empty finalizer should be deletedBad practice
FI: Explicit invocation of finalizerBad practice
FI: Finalizer nulls fieldsBad practice
FI: Finalizer only nulls fieldsBad practice
FI: Finalizer does not call superclass finalizerBad practice
FI: Finalizer nullifies superclass finalizerBad practice
FI: Finalizer does nothing but call superclass finalizerBad practice
HE: Class defines equals() but not hashCode()Bad practice
HE: Class defines equals() and uses Object.hashCode()Bad practice
HE: Class defines hashCode() but not equals()Bad practice
HE: Class defines hashCode() and uses Object.equals()Bad practice
HE: Class inherits equals() and uses Object.hashCode()Bad practice
IC: Superclass uses subclass during initializationBad practice
IMSE: Dubious catching of IllegalMonitorStateExceptionBad practice
ISC: Needless instantiation of class that only supplies static methodsBad practice
It: Iterator next() method can't throw NoSuchElement exceptionBad practice
J2EE: Store of non serializable object into HttpSessionBad practice
NP: Method with Boolean return type returns explicit nullBad practice
NP: Clone method may return nullBad practice
NP: equals() method does not check for null argumentBad practice
NP: toString method may return nullBad practice
Nm: Class names should start with an upper case letterBad practice
Nm: Class is not derived from an Exception, even though it is named as suchBad practice
Nm: Confusing method namesBad practice
Nm: Field names should start with a lower case letterBad practice
Nm: Use of identifier that is a keyword in later versions of JavaBad practice
Nm: Use of identifier that is a keyword in later versions of JavaBad practice
Nm: Method names should start with a lower case letterBad practice
Nm: Class names shouldn't shadow simple name of implemented interfaceBad practice
Nm: Class names shouldn't shadow simple name of superclassBad practice
Nm: Very confusing method namesBad practice
Nm: Method doesn't override method in superclass due to wrong package for parameterBad practice
ODR: Method may fail to close database resourceBad practice
ODR: Method may fail to close database resource on exceptionBad practice
OS: Method may fail to close streamBad practice
OS: Method may fail to close stream on exceptionBad practice
RC: Suspicious reference comparisonBad practice
RR: Method ignores results of InputStream.read()Bad practice
RR: Method ignores results of InputStream.skip()Bad practice
RV: Method ignores exceptional return valueBad practice
SI: Static initializer creates instance before all static final fields assignedBad practice
SW: Certain swing methods needs to be invoked in Swing threadBad practice
Se: Non-transient non-serializable instance field in serializable classBad practice
Se: Non-serializable class has a serializable inner classBad practice
Se: Non-serializable value stored into instance field of a serializable classBad practice
Se: Comparator doesn't implement SerializableBad practice
Se: Serializable inner classBad practice
Se: Method must be private in order for serialization to workBad practice
Se: serialVersionUID isn't finalBad practice
Se: serialVersionUID isn't longBad practice
Se: serialVersionUID isn't staticBad practice
Se: Class is Serializable but its superclass doesn't define a void constructorBad practice
Se: Class is Externalizable but doesn't define a void constructorBad practice
Se: The readResolve method must be declared with a return type of Object. Bad practice
Se: Transient field that isn't set by deserialization. Bad practice
SnVI: Class is Serializable, but doesn't define serialVersionUIDBad practice
UI: Usage of GetResource may be unsafe if class is extendedBad practice
BC: Impossible castCorrectness
BC: instanceof will always return falseCorrectness
BIT: Incompatible bit masksCorrectness
BIT: Check to see if ((...) & 0) == 0Correctness
BIT: Incompatible bit masksCorrectness
BIT: Bitwise OR of signed byte valueCorrectness
BIT: Check for sign of bitwise operationCorrectness
BOA: Class overrides a method implemented in super class Adapter wronglyCorrectness
Bx: Primitive value is unboxed and coerced for ternary operatorCorrectness
DLS: Useless assignment in return statementCorrectness
DLS: Dead store of class literalCorrectness
DLS: Overwritten incrementCorrectness
DMI: Bad constant value for monthCorrectness
DMI: hasNext method invokes nextCorrectness
DMI: Invocation of toString on an arrayCorrectness
DMI: Invocation of toString on an arrayCorrectness
DMI: Double.longBitsToDouble invoked on an intCorrectness
Dm: Can't use reflection to check for presence of annotation with default retentionCorrectness
EC: equals() used to compare array and nonarrayCorrectness
EC: Invocation of equals() on an array, which is equivalent to ==Correctness
EC: Call to equals() with null argumentCorrectness
EC: Call to equals() comparing unrelated class and interfaceCorrectness
EC: Call to equals() comparing different interface typesCorrectness
EC: Call to equals() comparing different typesCorrectness
EC: Using pointer equality to compare different typesCorrectness
Eq: equals method always returns falseCorrectness
Eq: equals method always returns trueCorrectness
Eq: equals method compares class names rather than class objectsCorrectness
Eq: Covariant equals() method defined for enumCorrectness
Eq: equals method fails for subtypesCorrectness
Eq: equals() method defined that doesn't override equals(Object)Correctness
Eq: equals() method defined that doesn't override Object.equals(Object)Correctness
Eq: equals method overrides equals in superclass and may not be symmetricCorrectness
Eq: Covariant equals() method defined, Object.equals(Object) inheritedCorrectness
FE: Doomed test for equality to NaNCorrectness
GC: No relationship between generic parameter and method argumentCorrectness
HE: Use of class without a hashCode() method in a hashed data structureCorrectness
ICAST: Integer shift by an amount not in the range 0..31Correctness
ICAST: int value cast to double and then passed to Math.ceilCorrectness
ICAST: int value cast to float and then passed to Math.roundCorrectness
IJU: JUnit assertion in run method will not be noticed by JUnitCorrectness
IJU: TestCase declares a bad suite method Correctness
IJU: TestCase has no testsCorrectness
IJU: TestCase implements setUp but doesn't call super.setUp()Correctness
IJU: TestCase implements a non-static suite method Correctness
IJU: TestCase implements tearDown but doesn't call super.tearDown()Correctness
IL: A container is added to itselfCorrectness
IL: An apparent infinite loopCorrectness
IL: An apparent infinite recursive loopCorrectness
IM: Integer multiply of result of integer remainderCorrectness
INT: Bad comparison of nonnegative value with negative constantCorrectness
INT: Bad comparison of signed byteCorrectness
INT: Integer remainder modulo 1Correctness
IO: Doomed attempt to append to an object output streamCorrectness
IP: A parameter is dead upon entry to a method but overwrittenCorrectness
JCIP: Fields of immutable classes should be finalCorrectness
MF: Class defines field that masks a superclass fieldCorrectness
MF: Method defines a variable that obscures a fieldCorrectness
NP: Null pointer dereferenceCorrectness
NP: Null pointer dereference in method on exception pathCorrectness
NP: Method does not check for null argumentCorrectness
NP: Null value is guaranteed to be dereferencedCorrectness
NP: Value is null and guaranteed to be dereferenced on exception pathCorrectness
NP: Method call passes null to a nonnull parameter Correctness
NP: Method may return null, but is declared @NonNullCorrectness
NP: A known null value is checked to see if it is an instance of a typeCorrectness
NP: Possible null pointer dereferenceCorrectness
NP: Possible null pointer dereference in method on exception pathCorrectness
NP: Method call passes null for unconditionally dereferenced parameterCorrectness
NP: Method call passes null for unconditionally dereferenced parameterCorrectness
NP: Non-virtual method call passes null for unconditionally dereferenced parameterCorrectness
NP: Store of null value into field annotated NonNullCorrectness
NP: Read of unwritten fieldCorrectness
Nm: Class defines equal(); should it be equals()?Correctness
Nm: Class defines hashcode(); should it be hashCode()?Correctness
Nm: Class defines tostring(); should it be toString()?Correctness
Nm: Apparent method/constructor confusionCorrectness
Nm: Very confusing method namesCorrectness
Nm: Method doesn't override method in superclass due to wrong package for parameterCorrectness
QBA: Method assigns boolean literal in boolean expressionCorrectness
RCN: Nullcheck of value previously dereferencedCorrectness
RE: Invalid syntax for regular expressionCorrectness
RE: File.separator used for regular expressionCorrectness
RE: "." used for regular expressionCorrectness
RV: Random value from 0 to 1 is coerced to the integer 0Correctness
RV: Bad attempt to compute absolute value of signed 32-bit hashcode Correctness
RV: Bad attempt to compute absolute value of signed 32-bit random integerCorrectness
RV: Exception created and dropped rather than thrownCorrectness
RV: Method ignores return valueCorrectness
SA: Double assignment of fieldCorrectness
SA: Self assignment of fieldCorrectness
SA: Self comparison of field with itselfCorrectness
SA: Nonsensical self computation involving a field (e.g., x & x)Correctness
SA: Double assignment of local variable Correctness
SA: Self comparison of value with itselfCorrectness
SA: Nonsensical self computation involving a variable (e.g., x & x)Correctness
SF: Dead store due to switch statement fall throughCorrectness
SIO: Unnecessary type check done using instanceof operatorCorrectness
SQL: Method attempts to access a prepared statement parameter with index 0Correctness
SQL: Method attempts to access a result set field with index 0Correctness
STI: Unneeded use of currentThread() call, to call interrupted() Correctness
STI: Static Thread.interrupted() method invoked on thread instanceCorrectness
Se: The readResolve method must not be declared as a static method. Correctness
TQ: Value annotated as carrying a type qualifier used where a value that must not carry that qualifier is requiredCorrectness
TQ: Value that might not carry a type qualifier reaches a use requiring that type qualifierCorrectness
TQ: Unknown value reaches a use which forbids values carrying type qualifier annotationCorrectness
TQ: Value annotated as never carrying a type qualifier used where value carrying that qualifier is requiredCorrectness
UCF: Useless control flow to next lineCorrectness
UMAC: Uncallable method defined in anonymous classCorrectness
UR: Uninitialized read of field in constructorCorrectness
UwF: Field only ever set to nullCorrectness
UwF: Unwritten fieldCorrectness
VA: Number of format-string arguments does not correspond to number of placeholdersCorrectness
VA: Primitive array passed to function expecting a variable number of object argumentsCorrectness
Dm: Consider using Locale parameterized version of invoked methodInternationalization
EI: May expose internal representation by returning reference to mutable objectMalicious code vulnerability
EI2: May expose internal representation by incorporating reference to mutable objectMalicious code vulnerability
FI: Finalizer should be protected, not publicMalicious code vulnerability
MS: May expose internal static state by storing a mutable object into a static fieldMalicious code vulnerability
MS: Field isn't final and can't be protected from malicious codeMalicious code vulnerability
MS: Public static method may expose internal representation by returning arrayMalicious code vulnerability
MS: Field should be both final and package protectedMalicious code vulnerability
MS: Field is a mutable arrayMalicious code vulnerability
MS: Field is a mutable HashtableMalicious code vulnerability
MS: Field should be moved out of an interface and made package protectedMalicious code vulnerability
MS: Field should be package protectedMalicious code vulnerability
MS: Field isn't final but should beMalicious code vulnerability
DC: Possible double check of fieldMultithreaded correctness
DL: Synchronization on Boolean could lead to deadlockMultithreaded correctness
DL: Synchronization on boxed primative could lead to deadlockMultithreaded correctness
DL: Synchronization on interned String could lead to deadlockMultithreaded correctness
DL: Synchronization on boxed primative valuesMultithreaded correctness
Dm: Monitor wait() called on ConditionMultithreaded correctness
Dm: A thread was created using the default empty run methodMultithreaded correctness
ESync: Empty synchronized blockMultithreaded correctness
IS: Inconsistent synchronizationMultithreaded correctness
IS: Field not guarded against concurrent accessMultithreaded correctness
JLM: Synchronization performed on java.util.concurrent LockMultithreaded correctness
LI: Incorrect lazy initialization of static fieldMultithreaded correctness
LI: Incorrect lazy initialization and update of static fieldMultithreaded correctness
ML: Synchronization on field in futile attempt to guard that fieldMultithreaded correctness
ML: Method synchronizes on an updated fieldMultithreaded correctness
MSF: Mutable servlet fieldMultithreaded correctness
MWN: Mismatched notify()Multithreaded correctness
MWN: Mismatched wait()Multithreaded correctness
NN: Naked notifyMultithreaded correctness
NP: Synchronize and null check on the same field.Multithreaded correctness
No: Using notify() rather than notifyAll()Multithreaded correctness
RS: Class's readObject() method is synchronizedMultithreaded correctness
Ru: Invokes run on a thread (did you mean to start it instead?)Multithreaded correctness
SC: Constructor invokes Thread.start()Multithreaded correctness
SP: Method spins on fieldMultithreaded correctness
STCAL: Call to static CalendarMultithreaded correctness
STCAL: Call to static DateFormatMultithreaded correctness
STCAL: Static CalendarMultithreaded correctness
STCAL: Static DateFormatMultithreaded correctness
SWL: Method calls Thread.sleep() with a lock heldMultithreaded correctness
TLW: Wait with two locks heldMultithreaded correctness
UG: Unsynchronized get method, synchronized set methodMultithreaded correctness
UL: Method does not release lock on all pathsMultithreaded correctness
UL: Method does not release lock on all exception pathsMultithreaded correctness
UW: Unconditional waitMultithreaded correctness
VO: A volatile reference to an array doesn't treat the array elements as volatileMultithreaded correctness
WL: Sychronization on getClass rather than class literalMultithreaded correctness
WS: Class's writeObject() method is synchronized but nothing else isMultithreaded correctness
Wa: Condition.await() not in loop Multithreaded correctness
Wa: Wait not in loop Multithreaded correctness
Bx: Primitive value is boxed and then immediately unboxedPerformance
Bx: Primitive value is boxed then unboxed to perform primitive coercionPerformance
Bx: Method allocates a boxed primitive just to call toStringPerformance
Bx: Method invokes inefficient floating-point Number constructor; use static valueOf insteadPerformance
Bx: Method invokes inefficient Number constructor; use static valueOf insteadPerformance
Dm: The equals and hashCode methods of URL are blockingPerformance
Dm: Maps and sets of URLs can be performance hogsPerformance
Dm: Method invokes inefficient Boolean constructor; use Boolean.valueOf(...) insteadPerformance
Dm: Explicit garbage collection; extremely dubious except in benchmarking codePerformance
Dm: Method allocates an object, only to get the class objectPerformance
Dm: Use the nextInt method of Random rather than nextDouble to generate a random integerPerformance
Dm: Method invokes inefficient new String(String) constructorPerformance
Dm: Method invokes inefficient String.equals(""); use String.length() == 0 insteadPerformance
Dm: Method invokes toString() method on a StringPerformance
Dm: Method invokes inefficient new String() constructorPerformance
HSC: Huge string constants is duplicated across multiple class filesPerformance
ITA: Method uses toArray() with zero-length array argumentPerformance
SBSC: Method concatenates strings using + in a loopPerformance
SIC: Should be a static inner classPerformance
SIC: Could be refactored into a named static inner classPerformance
SIC: Could be refactored into a static inner classPerformance
SS: Unread field: should this field be static?Performance
UM: Method calls static Math class method on a constant valuePerformance
UPM: Private method is never calledPerformance
UrF: Unread fieldPerformance
UuF: Unused fieldPerformance
WMI: Inefficient use of keySet iterator instead of entrySet iteratorPerformance
Dm: Hardcoded constant database passwordSecurity
Dm: Empty database passwordSecurity
HRS: HTTP cookie formed from untrusted inputSecurity
HRS: HTTP Response splitting vulnerabilitySecurity
SQL: Nonconstant string passed to execute method on an SQL statementSecurity
SQL: A prepared statement is generated from a nonconstant StringSecurity
XSS: JSP reflected cross site scripting vulnerabilitySecurity
XSS: Servlet reflected cross site scripting vulnerabilitySecurity
XSS: Servlet reflected cross site scripting vulnerabilitySecurity
BC: Questionable cast to abstract collection Dodgy
BC: Questionable cast to concrete collectionDodgy
BC: Unchecked/unconfirmed castDodgy
BC: instanceof will always return trueDodgy
CI: Class is final but declares protected fieldDodgy
DB: Method uses the same code for two branchesDodgy
DB: Method uses the same code for two switch clausesDodgy
DLS: Dead store to local variableDodgy
DLS: Dead store of null to local variableDodgy
DMI: Code contains a hard coded reference to an absolute pathnameDodgy
DMI: Non serializable object written to ObjectOutputDodgy
DMI: Invocation of substring(0), which returns the original valueDodgy
Dm: Thread passed where Runnable expectedDodgy
Eq: Class doesn't override equals in superclassDodgy
Eq: Unusual equals method Dodgy
FE: Test for floating point equalityDodgy
IA: Ambiguous invocation of either an inherited or outer methodDodgy
IC: Initialization circularityDodgy
ICAST: int division result cast to double or floatDodgy
ICAST: Result of integer multiplication cast to longDodgy
ICAST: Unsigned right shift cast to short/byteDodgy
IM: Computation of average could overflowDodgy
IM: Check for oddness that won't work for negative numbers Dodgy
INT: Vacuous comparison of integer valueDodgy
MTIA: Class extends Servlet class and uses instance variablesDodgy
MTIA: Class extends Struts Action class and uses instance variablesDodgy
NP: Immediate dereference of the result of readLine()Dodgy
NP: Load of known null valueDodgy
NP: Possible null pointer dereference due to return value of called methodDodgy
NP: Possible null pointer dereference on path that might be infeasibleDodgy
NS: Potentially dangerous use of non-short-circuit logicDodgy
NS: Questionable use of non-short-circuit logicDodgy
PZLA: Consider returning a zero length array rather than nullDodgy
QF: Complicated, subtle or wrong increment in for-loop Dodgy
RCN: Redundant comparison of non-null value to nullDodgy
RCN: Redundant comparison of two null valuesDodgy
RCN: Redundant nullcheck of value known to be non-nullDodgy
RCN: Redundant nullcheck of value known to be nullDodgy
REC: Exception is caught when Exception is not thrownDodgy
RI: Class implements same interface as superclassDodgy
RV: Method checks to see if result of String.indexOf is positiveDodgy
RV: Method discards result of readLine after checking if it is nonnullDodgy
RV: Remainder of hashCode could be negativeDodgy
RV: Remainder of 32-bit signed random integerDodgy
SA: Self assignment of local variableDodgy
SF: Switch statement found where one case falls through to the next caseDodgy
ST: Write to static field from instance methodDodgy
Se: private readResolve method not inherited by subclassesDodgy
Se: Transient field of class that isn't Serializable. Dodgy
UCF: Useless control flowDodgy
UwF: Field not initialized in constructorDodgy
XFB: Method directly allocates a specific implementation of xml interfacesDodgy

Descriptions

AM: Creates an empty jar file entry (AM_CREATES_EMPTY_JAR_FILE_ENTRY)

The code calls putNextEntry(), immediately followed by a call to closeEntry(). This results in an empty JarFile entry. The contents of the entry should be written to the JarFile between the calls to putNextEntry() and closeEntry().

AM: Creates an empty zip file entry (AM_CREATES_EMPTY_ZIP_FILE_ENTRY)

The code calls putNextEntry(), immediately followed by a call to closeEntry(). This results in an empty ZipFile entry. The contents of the entry should be written to the ZipFile between the calls to putNextEntry() and closeEntry().

BC: Equals method should not assume anything about the type of its argument (BC_EQUALS_METHOD_SHOULD_WORK_FOR_ALL_OBJECTS)

The equals(Object o) method shouldn't make any assumptions about the type of o. It should simply return false if o is not the same type as this.

BC: Random object created and used only once (DMI_RANDOM_USED_ONLY_ONCE)

This code creates a java.util.Random object, uses it to generate one random number, and then discards the Random object. This produces mediocre quality random numbers and is inefficient. If possible, rewrite the code so that the Random object is created once and saved, and each time a new random number is required invoke a method on the existing Random object to obtain it.

If it is important that the generated Random numbers not be guessable, you must not create a new Random for each random number; the values are too easily guessable. You should strongly consider using a java.security.SecureRandom instead (and avoid allocating a new SecureRandom for each random number needed).

BIT: Check for sign of bitwise operation (BIT_SIGNED_CHECK)

This method compares an expression such as

((event.detail & SWT.SELECTED) > 0)
. Using bit arithmetic and then comparing with the greater than operator can lead to unexpected results (of course depending on the value of SWT.SELECTED). If SWT.SELECTED is a negative number, this is a candidate for a bug. Even when SWT.SELECTED is not negative, it seems good practice to use '!= 0' instead of '> 0'.

Boris Bokowski

CN: Class implements Cloneable but does not define or use clone method (CN_IDIOM)

Class implements Cloneable but does not define or use the clone method.

CN: clone method does not call super.clone() (CN_IDIOM_NO_SUPER_CALL)

This non-final class defines a clone() method that does not call super.clone(). If this class ("A") is extended by a subclass ("B"), and the subclass B calls super.clone(), then it is likely that B's clone() method will return an object of type A, which violates the standard contract for clone().

If all clone() methods call super.clone(), then they are guaranteed to use Object.clone(), which always returns an object of the correct type.

CN: Class defines clone() but doesn't implement Cloneable (CN_IMPLEMENTS_CLONE_BUT_NOT_CLONEABLE)

This class defines a clone() method but the class doesn't implement Cloneable. There are some situations in which this is OK (e.g., you want to control how subclasses can clone themselves), but just make sure that this is what you intended.

Co: Abstract class defines covariant compareTo() method (CO_ABSTRACT_SELF)

This class defines a covariant version of compareTo().  To correctly override the compareTo() method in the Comparable interface, the parameter of compareTo() must have type java.lang.Object.

Co: Covariant compareTo() method defined (CO_SELF_NO_OBJECT)

This class defines a covariant version of compareTo().  To correctly override the compareTo() method in the Comparable interface, the parameter of compareTo() must have type java.lang.Object.

DE: Method might drop exception (DE_MIGHT_DROP)

This method might drop an exception.  In general, exceptions should be handled or reported in some way, or they should be thrown out of the method.

DE: Method might ignore exception (DE_MIGHT_IGNORE)

This method might ignore an exception.  In general, exceptions should be handled or reported in some way, or they should be thrown out of the method.

DP: Classloaders should only be created inside doPrivileged block (DP_CREATE_CLASSLOADER_INSIDE_DO_PRIVILEGED)

This code creates a classloader, which requires a security manager. If this code will be granted security permissions, but might be invoked by code that does not have security permissions, then the classloader creation needs to occur inside a doPrivileged block.

DP: Method invoked that should be only be invoked inside a doPrivileged block (DP_DO_INSIDE_DO_PRIVILEGED)

This code invokes a method that requires a security permission check. If this code will be granted security permissions, but might be invoked by code that does not have security permissions, then the invocation needs to occur inside a doPrivileged block.

Dm: Method invokes System.exit(...) (DM_EXIT)

Invoking System.exit shuts down the entire Java virtual machine. This should only been done when it is appropriate. Such calls make it hard or impossible for your code to be invoked by other code. Consider throwing a RuntimeException instead.

Dm: Method invokes dangerous method runFinalizersOnExit (DM_RUN_FINALIZERS_ON_EXIT)

Never call System.runFinalizersOnExit or Runtime.runFinalizersOnExit for any reason: they are among the most dangerous methods in the Java libraries. -- Joshua Bloch

ES: Comparison of String parameter using == or != (ES_COMPARING_PARAMETER_STRING_WITH_EQ)

This code compares a java.lang.String parameter for reference equality using the == or != operators. Requiring callers to pass only String constants or interned strings to a method is unnecessarily fragile, and rarely leads to measurable performance gains. Consider using the equals(Object) method instead.

ES: Comparison of String objects using == or != (ES_COMPARING_STRINGS_WITH_EQ)

This code compares java.lang.String objects for reference equality using the == or != operators. Unless both strings are either constants in a source file, or have been interned using the String.intern() method, the same string value may be represented by two different String objects. Consider using the equals(Object) method instead.

Eq: Abstract class defines covariant equals() method (EQ_ABSTRACT_SELF)

This class defines a covariant version of equals().  To correctly override the equals() method in java.lang.Object, the parameter of equals() must have type java.lang.Object.

Eq: Class defines compareTo(...) and uses Object.equals() (EQ_COMPARETO_USE_OBJECT_EQUALS)

This class defines a compareTo(...) method but inherits its equals() method from java.lang.Object. Generally, the value of compareTo should return zero if and only if equals returns true. If this is violated, weird and unpredictable failures will occur in classes such as PriorityQueue. In Java 5 the PriorityQueue.remove method uses the compareTo method, while in Java 6 it uses the equals method.

From the JavaDoc for the compareTo method in the Comparable interface:

It is strongly recommended, but not strictly required that (x.compareTo(y)==0) == (x.equals(y)). Generally speaking, any class that implements the Comparable interface and violates this condition should clearly indicate this fact. The recommended language is "Note: this class has a natural ordering that is inconsistent with equals."

Eq: Covariant equals() method defined (EQ_SELF_NO_OBJECT)

This class defines a covariant version of equals().  To correctly override the equals() method in java.lang.Object, the parameter of equals() must have type java.lang.Object.

FI: Empty finalizer should be deleted (FI_EMPTY)

Empty finalize() methods are useless, so they should be deleted.

FI: Explicit invocation of finalizer (FI_EXPLICIT_INVOCATION)

This method contains an explicit invocation of the finalize() method on an object.  Because finalizer methods are supposed to be executed once, and only by the VM, this is a bad idea.

If a connected set of objects beings finalizable, then the VM will invoke the finalize method on all the finalizable object, possibly at the same time in different threads. Thus, it is a particularly bad idea, in the finalize method for a class X, invoke finalize on objects referenced by X, because they may already be getting finalized in a separate thread.

FI: Finalizer nulls fields (FI_FINALIZER_NULLS_FIELDS)

This finalizer nulls out fields. This is usually an error, as it does not aid garbage collection, and the object is going to be garbage collected anyway.

FI: Finalizer only nulls fields (FI_FINALIZER_ONLY_NULLS_FIELDS)

This finalizer does nothing except null out fields. This is completely pointless, and requires that the object be garbage collected, finalized, and then garbage collected again. You should just remove the finalize method.

FI: Finalizer does not call superclass finalizer (FI_MISSING_SUPER_CALL)

This finalize() method does not make a call to its superclass's finalize() method.  So, any finalizer actions defined for the superclass will not be performed.  Add a call to super.finalize().

FI: Finalizer nullifies superclass finalizer (FI_NULLIFY_SUPER)

This empty finalize() method explicitly negates the effect of any finalizer defined by its superclass.  Any finalizer actions defined for the superclass will not be performed.  Unless this is intended, delete this method.

FI: Finalizer does nothing but call superclass finalizer (FI_USELESS)

The only thing this finalize() method does is call the superclass's finalize() method, making it redundant.  Delete it.

HE: Class defines equals() but not hashCode() (HE_EQUALS_NO_HASHCODE)

This class overrides equals(Object), but does not override hashCode().  Therefore, the class may violate the invariant that equal objects must have equal hashcodes.

HE: Class defines equals() and uses Object.hashCode() (HE_EQUALS_USE_HASHCODE)

This 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.

If you don't think instances of this class will ever be inserted into a HashMap/HashTable, the recommended hashCode implementation to use is:

public int hashCode() {
  assert false : "hashCode not designed";
  return 42; // any arbitrary constant will do 
  }

HE: Class defines hashCode() but not equals() (HE_HASHCODE_NO_EQUALS)

This class defines a hashCode() method but not an equals() method.  Therefore, the class may violate the invariant that equal objects must have equal hashcodes.

HE: Class defines hashCode() and uses Object.equals() (HE_HASHCODE_USE_OBJECT_EQUALS)

This class defines a hashCode() method but inherits its equals() method from java.lang.Object (which defines equality by comparing object references).  Although this will probably satisfy the contract that equal objects must have equal hashcodes, it is probably not what was intended by overriding the hashCode() method.  (Overriding hashCode() implies that the object's identity is based on criteria more complicated than simple reference equality.)

If you don't think instances of this class will ever be inserted into a HashMap/HashTable, the recommended hashCode implementation to use is:

public int hashCode() {
  assert false : "hashCode not designed";
  return 42; // any arbitrary constant will do 
  }

HE: Class inherits equals() and uses Object.hashCode() (HE_INHERITS_EQUALS_USE_HASHCODE)

This class inherits equals(Object) from an abstract superclass, and 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.

If you don't want to define a hashCode method, and/or don't believe the object will ever be put into a HashMap/Hashtable, define the hashCode() method to throw UnsupportedOperationException.

IC: Superclass uses subclass during initialization (IC_SUPERCLASS_USES_SUBCLASS_DURING_INITIALIZATION)

During the initialization of a class, the class makes an active use of a subclass. That subclass will not yet be initialized at the time of this use. For example, in the following code, foo will be null.

public class CircularClassInitialization {
	static class InnerClassSingleton extends CircularClassInitialization {
		static InnerClassSingleton singleton = new InnerClassSingleton();
	}
	
	static CircularClassInitialization foo = InnerClassSingleton.singleton;
}

IMSE: Dubious catching of IllegalMonitorStateException (IMSE_DONT_CATCH_IMSE)

IllegalMonitorStateException is generally only thrown in case of a design flaw in your code (calling wait or notify on an object you do not hold a lock on).

ISC: Needless instantiation of class that only supplies static methods (ISC_INSTANTIATE_STATIC_CLASS)

This class allocates an object that is based on a class that only supplies static methods. This object does not need to be created, just access the static methods directly using the class name as a qualifier.

It: Iterator next() method can't throw NoSuchElement exception (IT_NO_SUCH_ELEMENT)

This class implements the java.util.Iterator interface.  However, its next() method is not capable of throwing java.util.NoSuchElementException.  The next() method should be changed so it throws NoSuchElementException if is called when there are no more elements to return.

J2EE: Store of non serializable object into HttpSession (J2EE_STORE_OF_NON_SERIALIZABLE_OBJECT_INTO_SESSION)

This code seems to be storing a non-serializable object into an HttpSession. If this session is passivated or migrated, an error will result.

NP: Method with Boolean return type returns explicit null (NP_BOOLEAN_RETURN_NULL)

A method that returns either Boolean.TRUE, Boolean.FALSE or null is an accident waiting to happen. This method can be invoked as though it returned a value of type boolean, and the compiler will insert automatic unboxing of the Boolean value. If a null value is returned, this will result in a NullPointerException.

NP: Clone method may return null (NP_CLONE_COULD_RETURN_NULL)

This clone method seems to return null in some circumstances, but clone is never allowed to return a null value. If you are convinced this path is unreachable, throw an AssertionError instead.

NP: equals() method does not check for null argument (NP_EQUALS_SHOULD_HANDLE_NULL_ARGUMENT)

This implementation of equals(Object) violates the contract defined by java.lang.Object.equals() because it does not check for null being passed as the argument. All equals() methods should return false if passed a null value.

NP: toString method may return null (NP_TOSTRING_COULD_RETURN_NULL)

This toString method seems to return null in some circumstances. A liberal reading of the spec could be interpreted as allowing this, but it is probably a bad idea and could cause other code to break. Return the empty string or some other appropriate string rather than null.

Nm: Class names should start with an upper case letter (NM_CLASS_NAMING_CONVENTION)

Class names should be nouns, in mixed case with the first letter of each internal word capitalized. Try to keep your class names simple and descriptive. Use whole words-avoid acronyms and abbreviations (unless the abbreviation is much more widely used than the long form, such as URL or HTML).

Nm: Class is not derived from an Exception, even though it is named as such (NM_CLASS_NOT_EXCEPTION)

This class is not derived from another exception, but ends with 'Exception'. This will be confusing to users of this class.

Nm: Confusing method names (NM_CONFUSING)

The referenced methods have names that differ only by capitalization.

Nm: Field names should start with a lower case letter (NM_FIELD_NAMING_CONVENTION)

Names of fields that are not final should be in mixed case with a lowercase first letter and the first letters of subsequent words capitalized.

Nm: Use of identifier that is a keyword in later versions of Java (NM_FUTURE_KEYWORD_USED_AS_IDENTIFIER)

The identifier is a word that is reserversed as a keyword in later versions of Java, and your code will need to be changed in order to compile it in later versions of Java.

Nm: Use of identifier that is a keyword in later versions of Java (NM_FUTURE_KEYWORD_USED_AS_MEMBER_IDENTIFIER)

This identifier is used as a keyword in later versions of Java. This code, and any code that references this API, will need to be changed in order to compile it in later versions of Java.

Nm: Method names should start with a lower case letter (NM_METHOD_NAMING_CONVENTION)

Methods should be verbs, in mixed case with the first letter lowercase, with the first letter of each internal word capitalized.

Nm: Class names shouldn't shadow simple name of implemented interface (NM_SAME_SIMPLE_NAME_AS_INTERFACE)

This class/interface has a simple name that is identical to that of an implemented/extended interface, except that the interface is in a different package (e.g., alpha.Foo extends beta.Foo). This can be exceptionally confusing, create lots of situations in which you have to look at import statements to resolve references and creates many opportunities to accidently define methods that do not override methods in their superclasses.

Nm: Class names shouldn't shadow simple name of superclass (NM_SAME_SIMPLE_NAME_AS_SUPERCLASS)

This class has a simple name that is identical to that of its superclass, except that its superclass is in a different package (e.g., alpha.Foo extends beta.Foo). This can be exceptionally confusing, create lots of situations in which you have to look at import statements to resolve references and creates many opportunities to accidently define methods that do not override methods in their superclasses.

Nm: Very confusing method names (NM_VERY_CONFUSING_INTENTIONAL)

The referenced methods have names that differ only by capitalization. This is very confusing because if the capitalization were identical then one of the methods would override the other. From the existence of other methods, it seems that the existence of both of these methods is intentional, but is sure is confusing. You should try hard to eliminate one of them, unless you are forced to have both due to frozen APIs.

Nm: Method doesn't override method in superclass due to wrong package for parameter (NM_WRONG_PACKAGE_INTENTIONAL)

The method in the subclass doesn't override a similar method in a superclass because the type of a parameter doesn't exactly match the type of the corresponding parameter in the superclass. For example, if you have:

import alpha.Foo;
public class A {
  public int f(Foo x) { return 17; }
}
----
import beta.Foo;
public class B extends A {
  public int f(Foo x) { return 42; }
  public int f(alpha.Foo x) { return 27; }
}

The f(Foo) method defined in class B doesn't override the f(Foo) method defined in class A, because the argument types are Foo's from different packages.

In this case, the subclass does define a method with a signature identical to the method in the superclass, so this is presumably understood. However, such methods are exceptionally confusing. You should strongly consider removing or deprecating the method with the similar but not identical signature.

ODR: Method may fail to close database resource (ODR_OPEN_DATABASE_RESOURCE)

The method creates a database resource (such as a database connection or row set), does not assign it to any fields, pass it to other methods, or return it, and does not appear to close the object on all paths out of the method.  Failure to close database resources on all paths out of a method may result in poor performance, and could cause the application to have problems communicating with the database.

ODR: Method may fail to close database resource on exception (ODR_OPEN_DATABASE_RESOURCE_EXCEPTION_PATH)

The method creates a database resource (such as a database connection or row set), does not assign it to any fields, pass it to other methods, or return it, and does not appear to close the object on all exception paths out of the method.  Failure to close database resources on all paths out of a method may result in poor performance, and could cause the application to have problems communicating with the database.

OS: Method may fail to close stream (OS_OPEN_STREAM)

The method creates an IO stream object, does not assign it to any fields, pass it to other methods that might close it, or return it, and does not appear to close the stream on all paths out of the method.  This may result in a file descriptor leak.  It is generally a good idea to use a finally block to ensure that streams are closed.

OS: Method may fail to close stream on exception (OS_OPEN_STREAM_EXCEPTION_PATH)

The method creates an IO stream object, does not assign it to any fields, pass it to other methods, or return it, and does not appear to close it on all possible exception paths out of the method.  This may result in a file descriptor leak.  It is generally a good idea to use a finally block to ensure that streams are closed.

RC: Suspicious reference comparison (RC_REF_COMPARISON)

This method compares two reference values using the == or != operator, where the correct way to compare instances of this type is generally with the equals() method. Examples of classes which should generally not be compared by reference are java.lang.Integer, java.lang.Float, etc.

RR: Method ignores results of InputStream.read() (RR_NOT_CHECKED)

This method ignores the return value of one of the variants of java.io.InputStream.read() which can return multiple bytes.  If the return value is not checked, the caller will not be able to correctly handle the case where fewer bytes were read than the caller requested.  This is a particularly insidious kind of bug, because in many programs, reads from input streams usually do read the full amount of data requested, causing the program to fail only sporadically.

RR: Method ignores results of InputStream.skip() (SR_NOT_CHECKED)

This method ignores the return value of java.io.InputStream.skip() which can skip multiple bytes.  If the return value is not checked, the caller will not be able to correctly handle the case where fewer bytes were skipped than the caller requested.  This is a particularly insidious kind of bug, because in many programs, skips from input streams usually do skip the full amount of data requested, causing the program to fail only sporadically. With Buffered streams, however, skip() will only skip data in the buffer, and will routinely fail to skip the requested number of bytes.

RV: Method ignores exceptional return value (RV_RETURN_VALUE_IGNORED_BAD_PRACTICE)

This method returns a value that is not checked. The return value should be checked since it can indicate an unusual or unexpected function execution. For example, the File.delete() method returns false if the file could not be successfully deleted (rather than throwing an Exception). If you don't check the result, you won't notice if the method invocation signals unexpected behavior by returning an atypical return value.

SI: Static initializer creates instance before all static final fields assigned (SI_INSTANCE_BEFORE_FINALS_ASSIGNED)

The class's static initializer creates an instance of the class before all of the static final fields are assigned.

SW: Certain swing methods needs to be invoked in Swing thread (SW_SWING_METHODS_INVOKED_IN_SWING_THREAD)

(From JDC Tech Tip): The Swing methods show(), setVisible(), and pack() will create the associated peer for the frame. With the creation of the peer, the system creates the event dispatch thread. This makes things problematic because the event dispatch thread could be notifying listeners while pack and validate are still processing. This situation could result in two threads going through the Swing component-based GUI -- it's a serious flaw that could result in deadlocks or other related threading issues. A pack call causes components to be realized. As they are being realized (that is, not necessarily visible), they could trigger listener notification on the event dispatch thread.

Se: Non-transient non-serializable instance field in serializable class (SE_BAD_FIELD)

This Serializable class defines a non-primitive instance field which is neither transient, Serializable, or java.lang.Object, and does not appear to implement the Externalizable interface or the readObject() and writeObject() methods.  Objects of this class will not be deserialized correctly if a non-Serializable object is stored in this field.

Se: Non-serializable class has a serializable inner class (SE_BAD_FIELD_INNER_CLASS)

This Serializable class is an inner class of a non-serializable class. Thus, attempts to serialize it will also attempt to associate instance of the outer class with which it is associated, leading to a runtime error.

If possible, making the inner class a static inner class should solve the problem. Making the outer class serializable might also work, but that would mean serializing an instance of the inner class would always also serialize the instance of the outer class, which it often not what you really want.

Se: Non-serializable value stored into instance field of a serializable class (SE_BAD_FIELD_STORE)

A non-serializable value is stored into a non-transient field of a serializable class.

Se: Comparator doesn't implement Serializable (SE_COMPARATOR_SHOULD_BE_SERIALIZABLE)

This class implements the Comparator interface. You should consider whether or not it should also implement the Serializable interface. If a comparator is used to construct an ordered collection such as a TreeMap, then the TreeMap will be serializable only if the comparator is also serializable. As most comparators have little or no state, making them serializable is generally easy and good defensive programming.

Se: Serializable inner class (SE_INNER_CLASS)

This Serializable class is an inner class. Any attempt to serialize it will also serialize the associated outer instance. The outer instance is serializable, so this won't fail, but it might serialize a lot more data than intended. If possible, making the inner class a static inner class (also known as a nested class) should solve the problem.

Se: Method must be private in order for serialization to work (SE_METHOD_MUST_BE_PRIVATE)

This class implements the Serializable interface, and defines a method for custom serialization/deserialization. But since that method isn't declared private, it will be silently ignored by the serialization/deserialization API.

Se: serialVersionUID isn't final (SE_NONFINAL_SERIALVERSIONID)

This class defines a serialVersionUID field that is not final.  The field should be made final if it is intended to specify the version UID for purposes of serialization.

Se: serialVersionUID isn't long (SE_NONLONG_SERIALVERSIONID)

This class defines a serialVersionUID field that is not long.  The field should be made long if it is intended to specify the version UID for purposes of serialization.

Se: serialVersionUID isn't static (SE_NONSTATIC_SERIALVERSIONID)

This class defines a serialVersionUID field that is not static.  The field should be made static if it is intended to specify the version UID for purposes of serialization.

Se: Class is Serializable but its superclass doesn't define a void constructor (SE_NO_SUITABLE_CONSTRUCTOR)

This class implements the Serializable interface and its superclass does not. When such an object is deserialized, the fields of the superclass need to be initialized by invoking the void constructor of the superclass. Since the superclass does not have one, serialization and deserialization will fail at runtime.

Se: Class is Externalizable but doesn't define a void constructor (SE_NO_SUITABLE_CONSTRUCTOR_FOR_EXTERNALIZATION)

This class implements the Externalizable interface, but does not define a void constructor. When Externalizable objects are deserialized, they first need to be constructed by invoking the void constructor. Since this class does not have one, serialization and deserialization will fail at runtime.

Se: The readResolve method must be declared with a return type of Object. (SE_READ_RESOLVE_MUST_RETURN_OBJECT)

In order for the readResolve method to be recognized by the serialization mechanism, it must be declared to have a return type of Object.

Se: Transient field that isn't set by deserialization. (SE_TRANSIENT_FIELD_NOT_RESTORED)

This class contains a field that is updated at multiple places in the class, thus it seems to be part of the state of the class. However, since the field is marked as transient and not set in readObject or readResolve, it will contain the default value in any deserialized instance of the class.

SnVI: Class is Serializable, but doesn't define serialVersionUID (SE_NO_SERIALVERSIONID)

This class implements the Serializable interface, but does not define a serialVersionUID field.  A change as simple as adding a reference to a .class object will add synthetic fields to the class, which will unfortunately change the implicit serialVersionUID (e.g., adding a reference to String.class will generate a static field class$java$lang$String). Also, different source code to bytecode compilers may use different naming conventions for synthetic variables generated for references to class objects or inner classes. To ensure interoperability of Serializable across versions, consider adding an explicit serialVersionUID.

UI: Usage of GetResource may be unsafe if class is extended (UI_INHERITANCE_UNSAFE_GETRESOURCE)

Calling this.getClass().getResource(...) could give results other than expected if this class is extended by a class in another package.

BC: Impossible cast (BC_IMPOSSIBLE_CAST)

This cast will always throw a ClassCastException.

BC: instanceof will always return false (BC_IMPOSSIBLE_INSTANCEOF)

This instanceof test will always return false. Although this is safe, make sure it isn't an indication of some misunderstanding or some other logic error.

BIT: Incompatible bit masks (BIT_AND)

This method compares an expression of the form (a & C) to D, which will always compare unequal due to the specific values of constants C and D. This may indicate a logic error or typo.

BIT: Check to see if ((...) & 0) == 0 (BIT_AND_ZZ)

This method compares an expression of the form (a & 0) to 0, which will always compare equal. This may indicate a logic error or typo.

BIT: Incompatible bit masks (BIT_IOR)

This method compares an expression of the form (a | C) to D. which will always compare unequal due to the specific values of constants C and D. This may indicate a logic error or typo.

Typically, this bug occurs because the code wants to perform a membership test in a bit set, but uses the bitwise OR operator ("|") instead of bitwise AND ("&").

BIT: Bitwise OR of signed byte value (BIT_IOR_OF_SIGNED_BYTE)

Loads a value from a byte array and performs a bitwise OR with that value. Values loaded from a byte array are sign extended to 32 bits before any any bitwise operations are performed on the value. Thus, if b[0] contains the value 0xff, and x is initially 0, then the code ((x << 8) | b[0]) will sign extend 0xff to get 0xffffffff, and thus give the value 0xffffffff as the result.

In particular, the following code for packing a byte array into an int is badly wrong:

int result = 0; for(int i = 0; i < 4; i++) result = ((result << 8) | b[i]);

The following idiom will work instead:

int result = 0; for(int i = 0; i < 4; i++) result = ((result << 8) | (b[i] &s; 0xff));

BIT: Check for sign of bitwise operation (BIT_SIGNED_CHECK_HIGH_BIT)

This method compares an expression such as

((event.detail & SWT.SELECTED) > 0)
. Using bit arithmetic and then comparing with the greater than operator can lead to unexpected results (of course depending on the value of SWT.SELECTED). If SWT.SELECTED is a negative number, this is a candidate for a bug. Even when SWT.SELECTED is not negative, it seems good practice to use '!= 0' instead of '> 0'.

Boris Bokowski

BOA: Class overrides a method implemented in super class Adapter wrongly (BOA_BADLY_OVERRIDDEN_ADAPTER)

This method overrides a method found in a parent class, where that class is an Adapter that implements a listener defined in the java.awt.event or javax.swing.event package. As a result, this method will not get called when the event occurs.

Bx: Primitive value is unboxed and coerced for ternary operator (BX_UNBOXED_AND_COERCED_FOR_TERNARY_OPERATOR)

A wrapped primitive value is unboxed and converted to another primitive type as part of the evaluation of a conditional ternary operator (the b ? e1 : e2 operator). The semantics of Java mandate that if e1 and e2 are wrapped numeric values, the values are unboxed and converted/coerced to their common type (e.g, if e1 is of type Integer and e2 is of type Float, then e1 is unboxed, converted to a floating point value, and boxed. See JLS Section 15.25.

DLS: Useless assignment in return statement (DLS_DEAD_LOCAL_STORE_IN_RETURN)

This statement assigns to a local variable in a return statement. This assignment has effect. Please verify that this statement does the right thing.

DLS: Dead store of class literal (DLS_DEAD_STORE_OF_CLASS_LITERAL)

This instruction assigns a class literal to a variable and then never uses it. The behavior of this differs in Java 1.4 and in Java 5. In Java 1.4 and earlier, a reference to Foo.class would force the static initializer for Foo to be executed, if it has not been executed already. In Java 5 and later, it does not.

See Sun's article on Java SE compatibility for more details and examples, and suggestions on how to force class initialization in Java 5.

DLS: Overwritten increment (DLS_OVERWRITTEN_INCREMENT)

The code performs an increment operation (e.g., i++) and then immediately overwrites it. For example, i = i++ immediately overwrites the incremented value with the original value.

DMI: Bad constant value for month (DMI_BAD_MONTH)

This code passes a constant month value outside the expected range of 0..11 to a method.

DMI: hasNext method invokes next (DMI_CALLING_NEXT_FROM_HASNEXT)

The hasNext() method invokes the next() method. This is almost certainly wrong, since the hasNext() method is not supposed to change the state of the iterator, and the next method is supposed to change the state of the iterator.

DMI: Invocation of toString on an array (DMI_INVOKING_TOSTRING_ON_ANONYMOUS_ARRAY)

The code invokes toString on an (anonymous) array. Calling toString on an array generates a fairly useless result such as [C@16f0472. Consider using Arrays.toString to convert the array into a readable String that gives the contents of the array. See Programming Puzzlers, chapter 3, puzzle 12.

DMI: Invocation of toString on an array (DMI_INVOKING_TOSTRING_ON_ARRAY)

The code invokes toString on an array, which will generate a fairly useless result such as [C@16f0472. Consider using Arrays.toString to convert the array into a readable String that gives the contents of the array. See Programming Puzzlers, chapter 3, puzzle 12.

DMI: Double.longBitsToDouble invoked on an int (DMI_LONG_BITS_TO_DOUBLE_INVOKED_ON_INT)

The Double.longBitsToDouble method is invoked, but a 32 bit int value is passed as an argument. This almostly certainly is not intended and is unlikely to give the intended result.

Dm: Can't use reflection to check for presence of annotation with default retention (DMI_ANNOTATION_IS_NOT_VISIBLE_TO_REFLECTION)

Unless an annotation has itself been annotated with a @Retention other than the default of source-only retention, the annotation isn't retained in the classfile and can't be observed using reflection (e.g., by using the isAnnotationPresent method). .

EC: equals() used to compare array and nonarray (EC_ARRAY_AND_NONARRAY)

This method invokes the .equals(Object o) to compare an array and a reference that doesn't seem to be an array. If things being compared are of different types, they are guaranteed to be unequal and the comparison is almost certainly an error. Even if they are both arrays, the equals method on arrays only determines of the two arrays are the same object. To compare the contents of the arrays, use java.util.Arrays.equals(Object[], Object[]).

EC: Invocation of equals() on an array, which is equivalent to == (EC_BAD_ARRAY_COMPARE)

This method invokes the .equals(Object o) method on an array. Since arrays do not override the equals method of Object, calling equals on an array is the same as comparing their addresses. To compare the contents of the arrays, use java.util.Arrays.equals(Object[], Object[]).

EC: Call to equals() with null argument (EC_NULL_ARG)

This method calls equals(Object), passing a null value as the argument. According to the contract of the equals() method, this call should always return false.

EC: Call to equals() comparing unrelated class and interface (EC_UNRELATED_CLASS_AND_INTERFACE)

This method calls equals(Object) on two references, one of which is a class and the other an interface, where neither the class nor any of its non-abstract subclasses implement the interface. Therefore, the objects being compared are unlikely to be members of the same class at runtime (unless some application classes were not analyzed, or dynamic class loading can occur at runtime). According to the contract of equals(), objects of different classes should always compare as unequal; therefore, according to the contract defined by java.lang.Object.equals(Object), the result of this comparison will always be false at runtime.

EC: Call to equals() comparing different interface types (EC_UNRELATED_INTERFACES)

This method calls equals(Object) on two references of unrelated interface types, where neither is a subtype of the other, and there are no known non-abstract classes which implement both interfaces. Therefore, the objects being compared are unlikely to be members of the same class at runtime (unless some application classes were not analyzed, or dynamic class loading can occur at runtime). According to the contract of equals(), objects of different classes should always compare as unequal; therefore, according to the contract defined by java.lang.Object.equals(Object), the result of this comparison will always be false at runtime.

EC: Call to equals() comparing different types (EC_UNRELATED_TYPES)

This method calls equals(Object) on two references of different class types with no common subclasses. Therefore, the objects being compared are unlikely to be members of the same class at runtime (unless some application classes were not analyzed, or dynamic class loading can occur at runtime). According to the contract of equals(), objects of different classes should always compare as unequal; therefore, according to the contract defined by java.lang.Object.equals(Object), the result of this comparison will always be false at runtime.

EC: Using pointer equality to compare different types (EC_UNRELATED_TYPES_USING_POINTER_EQUALITY)

This method uses using pointer equality to compare two references that seem to be of different types. The result of this comparison will always be false at runtime.

Eq: equals method always returns false (EQ_ALWAYS_FALSE)

This class defines an equals method that always returns false. This means that an object is not equal to itself, and it is impossible to create useful Maps or Sets of this class. More fundementally, it means that equals is not reflexive, one of the requirements of the equals method.

The likely intended semantics are object identity: that an object is equal to itself. This is the behavior inherited from class Object. If you need to override an equals inherited from a different superclass, you can use use:

public boolean equals(Object o) { return this == o; }

Eq: equals method always returns true (EQ_ALWAYS_TRUE)

This class defines an equals method that always returns true. This is imaginative, but not very smart. Plus, it means that the equals method is not symmetric.

Eq: equals method compares class names rather than class objects (EQ_COMPARING_CLASS_NAMES)

This method checks to see if two objects are the same class by checking to see if the names of their classes are equal. You can have different classes with the same name if they are loaded by different class loaders. Just check to see if the class objects are the same.

Eq: Covariant equals() method defined for enum (EQ_DONT_DEFINE_EQUALS_FOR_ENUM)

This class defines an enumeration, and equality on enumerations are defined using object identity. Definine a covariant equals method for an enumeration value is exceptionally bad practice, since it would likely result in having two different enumeration values that compare as equals using the covariant enum method, and as not equal when compared normally. Don't do it.

Eq: equals method fails for subtypes (EQ_GETCLASS_AND_CLASS_CONSTANT)

This class has an equals method that will be broken if it is inherited by subclasses. It compares a class literal with the class of the argument (e.g., in class Foo it might check if Foo.class == o.getClass()). It is better to check if this.getClass() == o.getClass().

Eq: equals() method defined that doesn't override equals(Object) (EQ_OTHER_NO_OBJECT)

This class defines an equals() method, that doesn't override the normal equals(Object) method defined in the base java.lang.Object class.  Instead, it inherits an equals(Object) method from a superclass. The class should probably define a boolean equals(Object) method.

Eq: equals() method defined that doesn't override Object.equals(Object) (EQ_OTHER_USE_OBJECT)

This class defines an equals() method, that doesn't override the normal equals(Object) method defined in the base java.lang.Object class.  The class should probably define a boolean equals(Object) method.

Eq: equals method overrides equals in superclass and may not be symmetric (EQ_OVERRIDING_EQUALS_NOT_SYMMETRIC)

This class defines an equals method that overrides an equals method in a superclass. Both equals methods methods use instanceof in the determination of whether two objects are equal. This is fraught with peril, since it is important that the equals method is symetrical (in other words, a.equals(b) == b.equals(a)). If B is a subtype of A, and A's equals method checks that the argument is an instanceof A, and B's equals method checks that the argument is an instanceof B, it is quite likely that the equivalence relation defined by these methods is not symmetric.

Eq: Covariant equals() method defined, Object.equals(Object) inherited (EQ_SELF_USE_OBJECT)

This class defines a covariant version of the equals() method, but inherits the normal equals(Object) method defined in the base java.lang.Object class.  The class should probably define a boolean equals(Object) method.

FE: Doomed test for equality to NaN (FE_TEST_IF_EQUAL_TO_NOT_A_NUMBER)

This code checks to see if a floating point value is equal to the special Not A Number value (e.g., if (x == Double.NaN)). However, because of the special semantics of NaN, no value is equal to Nan, including NaN. Thus, x == Double.NaN always evaluates to false. To check to see if a value contained in x is the special Not A Number value, use Double.isNaN(x) (or Float.isNaN(x) if x is floating point precision).

GC: No relationship between generic parameter and method argument (GC_UNRELATED_TYPES)

This call to a generic container's method contains an argument with a different class type from that of the container's parameter. Therefore, it is unlikely that the container contains any objects with the same type as the method argument used here.

HE: Use of class without a hashCode() method in a hashed data structure (HE_USE_OF_UNHASHABLE_CLASS)

A class defines an equals(Object) method but not a hashCode() method, and thus doesn't fulfill the requirement that equal Objects have equal hashCodes. An instance of this class is used in a hash data structure, making the need to fix this problem of highest importance.

ICAST: Integer shift by an amount not in the range 0..31 (ICAST_BAD_SHIFT_AMOUNT)

The code performs an integer shift by a constant amount outside the range 0..31. The effect of this is to use the lower 5 bits of the integer value to decide how much to shift by. This probably isn't want was expected, and it at least confusing.

ICAST: int value cast to double and then passed to Math.ceil (ICAST_INT_CAST_TO_DOUBLE_PASSED_TO_CEIL)

This code converts an int value to a double precision floating point number and then passing the result to the Math.ceil() function, which rounds a double to the next higher integer value. This operation should always be a no-op, since the converting an integer to a double should give a number with no fractional part. It is likely that the operation that generated the value to be passed to Math.ceil was intended to be performed using double precision floating point arithmetic.

ICAST: int value cast to float and then passed to Math.round (ICAST_INT_CAST_TO_FLOAT_PASSED_TO_ROUND)

This code converts an int value to a float precision floating point number and then passing the result to the Math.round() function, which returns the int/long closest to the argument. This operation should always be a no-op, since the converting an integer to a float should give a number with no fractional part. It is likely that the operation that generated the value to be passed to Math.round was intended to be performed using floating point arithmetic.

IJU: JUnit assertion in run method will not be noticed by JUnit (IJU_ASSERT_METHOD_INVOKED_FROM_RUN_METHOD)

A JUnit assertion is performed in a run method. Failed JUnit assertions just result in exceptions being thrown. Thus, if this exception occurs in a thread other than the thread that invokes the test method, the exception will terminate the thread but not result in the test failing.

IJU: TestCase declares a bad suite method (IJU_BAD_SUITE_METHOD)

Class is a JUnit TestCase and defines a suite() method. However, the suite method needs to be declared as either

public static junit.framework.Test suite()
or
public static junit.framework.TestSuite suite()

IJU: TestCase has no tests (IJU_NO_TESTS)

Class is a JUnit TestCase but has not implemented any test methods

IJU: TestCase implements setUp but doesn't call super.setUp() (IJU_SETUP_NO_SUPER)

Class is a JUnit TestCase and implements the setUp method. The setUp method should call super.setUp(), but doesn't.

IJU: TestCase implements a non-static suite method (IJU_SUITE_NOT_STATIC)

Class is a JUnit TestCase and implements the suite() method. The suite method should be declared as being static, but isn't.

IJU: TestCase implements tearDown but doesn't call super.tearDown() (IJU_TEARDOWN_NO_SUPER)

Class is a JUnit TestCase and implements the tearDown method. The tearDown method should call super.tearDown(), but doesn't.

IL: A container is added to itself (IL_CONTAINER_ADDED_TO_ITSELF)

A container is added to itself. As a result, computing the hashCode of this set will throw a StackOverflowException.

IL: An apparent infinite loop (IL_INFINITE_LOOP)

This loop doesn't seem to have a way to terminate (other than by perhaps throwing an exception).

IL: An apparent infinite recursive loop (IL_INFINITE_RECURSIVE_LOOP)

This method unconditionally invokes itself. This would seem to indicate an infinite recursive loop that will result in a stack overflow.

IM: Integer multiply of result of integer remainder (IM_MULTIPLYING_RESULT_OF_IREM)

The code multiplies the result of an integer remaining by an integer constant. Be sure you don't have your operator precedence confused. For example i % 60 * 1000 is (i % 60) * 1000, not i % (60 * 1000).

INT: Bad comparison of nonnegative value with negative constant (INT_BAD_COMPARISON_WITH_NONNEGATIVE_VALUE)

This code compares a value that is guaranteed to be non-negative with a negative constant.

INT: Bad comparison of signed byte (INT_BAD_COMPARISON_WITH_SIGNED_BYTE)

Signed bytes can only have a value in the range -128 to 127. Comparing a signed byte with a value outside that range is vacuous and likely to be incorrect. To convert a signed byte b to an unsigned value in the range 0..255, use 0xff & b

INT: Integer remainder modulo 1 (INT_BAD_REM_BY_1)

Any expression (exp % 1) is guaranteed to always return zero. Did you mean (exp & 1) or (exp % 2) instead?

IO: Doomed attempt to append to an object output stream (IO_APPENDING_TO_OBJECT_OUTPUT_STREAM)

This code opens a file in append mode and then wraps the result in an object output stream. This won't allow you to append to an existing object output stream stored in a file. If you want to be able to append to an object output stream, you need to keep the object output stream open.

The only situation in which opening a file in append mode and the writing an object output stream could work is if on reading the file you plan to open it in random access mode and seek to the byte offset where the append started.

TODO: example.

IP: A parameter is dead upon entry to a method but overwritten (IP_PARAMETER_IS_DEAD_BUT_OVERWRITTEN)

The initial value of this parameter is ignored, and the parameter is overwritten here. This often indicates a mistaken belief that the write to the parameter will be conveyed back to the caller.

JCIP: Fields of immutable classes should be final (JCIP_FIELD_ISNT_FINAL_IN_IMMUTABLE_CLASS)

The class is annotated with net.jcip.annotations.Immutable, and the rules for that annotation require that all fields are final. .

MF: Class defines field that masks a superclass field (MF_CLASS_MASKS_FIELD)

This class defines a field with the same name as a visible instance field in a superclass. This is confusing, and may indicate an error if methods update or access one of the fields when they wanted the other.

MF: Method defines a variable that obscures a field (MF_METHOD_MASKS_FIELD)

This method defines a local variable with the same name as a field in this class or a superclass. This may cause the method to read an uninitialized value from the field, leave the field uninitialized, or both.

NP: Null pointer dereference (NP_ALWAYS_NULL)

A null pointer is dereferenced here.  This will lead to a NullPointerException when the code is executed.

NP: Null pointer dereference in method on exception path (NP_ALWAYS_NULL_EXCEPTION)

A pointer which is null on an exception path is dereferenced here.  This will lead to a NullPointerException when the code is executed.  Note that because FindBugs currently does not prune infeasible exception paths, this may be a false warning.

Also note that FindBugs considers the default case of a switch statement to be an exception path, since the default case is often infeasible.

NP: Method does not check for null argument (NP_ARGUMENT_MIGHT_BE_NULL)

A parameter to this method has been identified as a value that should always be checked to see whether or not it is null, but it is being dereferenced without a preceding null check.

NP: Null value is guaranteed to be dereferenced (NP_GUARANTEED_DEREF)

There is a statement or branch that if executed guarantees that a value is null at this point, and that value that is guaranteed to be dereferenced (except on forward paths involving runtime exceptions).

NP: Value is null and guaranteed to be dereferenced on exception path (NP_GUARANTEED_DEREF_ON_EXCEPTION_PATH)

There is a statement or branch on an exception path that if executed guarantees that a value is null at this point, and that value that is guaranteed to be dereferenced (except on forward paths involving runtime exceptions).

NP: Method call passes null to a nonnull parameter (NP_NONNULL_PARAM_VIOLATION)

This method passes a null value as the parameter of a method which must be nonnull. Either this parameter has been explicitly marked as @Nonnull, or analysis has determined that this parameter is always dereferenced.

NP: Method may return null, but is declared @NonNull (NP_NONNULL_RETURN_VIOLATION)

This method may return a null value, but the method (or a superclass method which it overrides) is declared to return @NonNull.

NP: A known null value is checked to see if it is an instance of a type (NP_NULL_INSTANCEOF)

This instanceof test will always return false, since the value being checked is guaranteed to be null. Although this is safe, make sure it isn't an indication of some misunderstanding or some other logic error.

NP: Possible null pointer dereference (NP_NULL_ON_SOME_PATH)

There is a branch of statement that, if executed, guarantees that a null value will be dereferenced, which would generate a NullPointerException when the code is executed. Of course, the problem might be that the branch or statement is infeasible and that the null pointer exception can't ever be executed; deciding that is beyond the ability of FindBugs.

NP: Possible null pointer dereference in method on exception path (NP_NULL_ON_SOME_PATH_EXCEPTION)

A reference value which is null on some exception control path is dereferenced here.  This may lead to a NullPointerException when the code is executed.  Note that because FindBugs currently does not prune infeasible exception paths, this may be a false warning.

Also note that FindBugs considers the default case of a switch statement to be an exception path, since the default case is often infeasible.

NP: Method call passes null for unconditionally dereferenced parameter (NP_NULL_PARAM_DEREF)

This method call passes a null value to a method which might dereference it unconditionally.

NP: Method call passes null for unconditionally dereferenced parameter (NP_NULL_PARAM_DEREF_ALL_TARGETS_DANGEROUS)

A possibly-null value is passed at a call site where all known target methods will unconditionally dereference it. This is very likely to result in a null pointer exception.

NP: Non-virtual method call passes null for unconditionally dereferenced parameter (NP_NULL_PARAM_DEREF_NONVIRTUAL)

A possibly-null value is passed to a method which unconditionally dereferences it. This will almost certainly result in a null pointer exception.

NP: Store of null value into field annotated NonNull (NP_STORE_INTO_NONNULL_FIELD)

A value that could be null is stored into a field that has been annotated as NonNull.

NP: Read of unwritten field (NP_UNWRITTEN_FIELD)

The program is dereferencing a field that does not seem to ever have a non-null value written to it. Dereferencing this value will generate a null pointer exception.

Nm: Class defines equal(); should it be equals()? (NM_BAD_EQUAL)

This class defines a method equal(Object).  This method does not override the equals(Object) method in java.lang.Object, which is probably what was intended.

Nm: Class defines hashcode(); should it be hashCode()? (NM_LCASE_HASHCODE)

This class defines a method called hashcode().  This method does not override the hashCode() method in java.lang.Object, which is probably what was intended.

Nm: Class defines tostring(); should it be toString()? (NM_LCASE_TOSTRING)

This class defines a method called tostring().  This method does not override the toString() method in java.lang.Object, which is probably what was intended.

Nm: Apparent method/constructor confusion (NM_METHOD_CONSTRUCTOR_CONFUSION)

This regular method has the same name as the class it is defined in. It is likely that this was intended to be a constructor. If it was intended to be a constructor, remove the declaration of a void return value. If you had accidently defined this method, realized the mistake, defined a proper constructor but can't get rid of this method due to backwards compatibility, deprecate the method.

Nm: Very confusing method names (NM_VERY_CONFUSING)

The referenced methods have names that differ only by capitalization. This is very confusing because if the capitalization were identical then one of the methods would override the other.

Nm: Method doesn't override method in superclass due to wrong package for parameter (NM_WRONG_PACKAGE)

The method in the subclass doesn't override a similar method in a superclass because the type of a parameter doesn't exactly match the type of the corresponding parameter in the superclass. For example, if you have:

import alpha.Foo;
public class A {
  public int f(Foo x) { return 17; }
}
----
import beta.Foo;
public class B extends A {
  public int f(Foo x) { return 42; }
}

The f(Foo) method defined in class B doesn't override the f(Foo) method defined in class A, because the argument types are Foo's from different packages.

QBA: Method assigns boolean literal in boolean expression (QBA_QUESTIONABLE_BOOLEAN_ASSIGNMENT)

This method assigns a literal boolean value (true or false) to a boolean variable inside an if or while expression. Most probably this was supposed to be a boolean comparison using ==, not an assignment using =.

RCN: Nullcheck of value previously dereferenced (RCN_REDUNDANT_NULLCHECK_WOULD_HAVE_BEEN_A_NPE)

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. Essentially, this code and the previous dereference disagree as to whether this value is allowed to be null. Either the check is redundant or the previous dereference is erroneous.

RE: Invalid syntax for regular expression (RE_BAD_SYNTAX_FOR_REGULAR_EXPRESSION)

The code here uses a regular expression that is invalid according to the syntax for regular expressions. This statement will throw a PatternSyntaxException when executed.

RE: File.separator used for regular expression (RE_CANT_USE_FILE_SEPARATOR_AS_REGULAR_EXPRESSION)

The code here uses File.separator where a regular expression is required. This will fail on Windows platforms, where the File.separator is a backslash, which is interpreted in a regular expression as an escape character. Amoung other options, you can just use File.separatorChar=='\\' & "\\\\" : File.separator instead of File.separator

RE: "." used for regular expression (RE_POSSIBLE_UNINTENDED_PATTERN)

A String function is being invoked and "." is being passed to a parameter that takes a regular expression as an argument. Is this what you intended? For example s.replaceAll(".", "/") will return a String in which every character has been replaced by a / character.

RV: Random value from 0 to 1 is coerced to the integer 0 (RV_01_TO_INT)

A random value from 0 to 1 is being coerced to the integer value 0. You probably want to multiple the random value by something else before coercing it to an integer, or use the Random.nextInt(n) method.

RV: Bad attempt to compute absolute value of signed 32-bit hashcode (RV_ABSOLUTE_VALUE_OF_HASHCODE)

This code generates a hashcode and then computes the absolute value of that hashcode. If the hashcode is Integer.MIN_VALUE, then the result will be negative as well (since Math.abs(Integer.MIN_VALUE) == Integer.MIN_VALUE).

RV: Bad attempt to compute absolute value of signed 32-bit random integer (RV_ABSOLUTE_VALUE_OF_RANDOM_INT)

This code generates a random signed integer and then computes the absolute value of that random integer. If the number returned by the random number generator is Integer.MIN_VALUE, then the result will be negative as well (since Math.abs(Integer.MIN_VALUE) == Integer.MIN_VALUE).

RV: Exception created and dropped rather than thrown (RV_EXCEPTION_NOT_THROWN)

This code creates an exception (or error) object, but doesn't do anything with it. For example, something like

if (x < 0)
  new IllegalArgumentException("x must be nonnegative");

It was probably the intent of the programmer to throw the created exception:

if (x < 0)
  throw new IllegalArgumentException("x must be nonnegative");

RV: Method ignores return value (RV_RETURN_VALUE_IGNORED)

The return value of this method should be checked. One common cause of this warning is to invoke a method on an immutable object, thinking that it updates the object. For example, in the following code fragment,

String dateString = getHeaderField(name);
dateString.trim();

the programmer seems to be thinking that the trim() method will update the String referenced by dateString. But since Strings are immutable, the trim() function returns a new String value, which is being ignored here. The code should be corrected to:

String dateString = getHeaderField(name);
dateString = dateString.trim();

SA: Double assignment of field (SA_FIELD_DOUBLE_ASSIGNMENT)

This method contains a double assignment of a field; e.g.

  int x,y;
  public void foo() {
    x = x = 17;
  }

Assigning to a field twice is useless, and may indicate a logic error or typo.

SA: Self assignment of field (SA_FIELD_SELF_ASSIGNMENT)

This method contains a self assignment of a field; e.g.

  int x;
  public void foo() {
    x = x;
  }

Such assignments are useless, and may indicate a logic error or typo.

SA: Self comparison of field with itself (SA_FIELD_SELF_COMPARISON)

This method compares a field with itself, and may indicate a typo or a logic error. Make sure that you are comparing the right things.

SA: Nonsensical self computat