Sunday, 20 March 2016

FindBugs rules - Correctness


Correctness - rules provided by FindBugs

Impossible cast
This cast will always throw a ClassCastException.
FindBugs tracks type information from instanceof checks, and also uses more precise information about the types of values returned from methods and loaded from fields.
Thus, it may have more precise information that just the declared type of a variable, and can use this to determine that a cast will always throw an exception at runtime.

Impossible downcast
This cast will always throw a ClassCastException.
The analysis believes it knows the precise type of the value being cast, and the attempt to downcast it to a subtype will always fail by throwing a ClassCastException.

Impossible downcast of toArray() result
This code is casting the result of calling toArray() on a collection to a type more specific than Object[], as in:
String[] getAsArray(Collection c) {
  return (String[]) c.toArray();
}
This will usually fail by throwing a ClassCastException.
The toArray() of almost all collections return an Object[].
They can't really do anything else, since the Collection object has no reference to the declared generic type of the collection.
The correct way to do get an array of a specific type from a collection is to use
c.toArray(new String[]);
or
c.toArray(new String[c.size()]);
(the latter is slightly more efficient)

There is one common/known exception exception to this.
The toArray() method of lists returned by Arrays.asList(...) will return a covariantly typed array.
For example, Arrays.asArray(new String[] { "a" }).toArray() will return a String [].
FindBugs attempts to detect and suppress such cases, but may miss some.

instanceof will always return false
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.

Bitwise add of signed byte value
Adds a byte value and a value which is known to have the 8 lower bits clear.
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] & 0xff));

Incompatible bit masks
This method compares an expression of the form (e & 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.

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

Incompatible bit masks
This method compares an expression of the form (e | 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 ("&").

Bitwise OR of signed byte value
Loads a byte value (e.g., a value loaded from a byte array or returned by a method with return type byte) and performs a bitwise OR with that value.
Byte values 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] & 0xff));

Check for sign of bitwise operation
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'.

Class overrides a method implemented in super class Adapter wrongly
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.

32 bit int shifted by an amount not in the range -31..31
The code performs shift of a 32 bit int by a constant amount outside the range -31..31.
The effect of this is to use the lower 5 bits of the integer value to decide how much to shift by (e.g., shifting by 40 bits is the same as shifting by 8 bits, and shifting by 32 bits is the same as shifting by zero bits).
This probably isn't what was expected, and it is at least confusing.

Primitive value is 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.

compareTo()/compare() returns Integer.MIN_VALUE
In some situation, this compareTo or compare method returns the constant Integer.MIN_VALUE, which is an exceptionally bad practice.
The only thing that matters about the return value of compareTo is the sign of the result.
But people will sometimes negate the return value of compareTo, expecting that this will negate the sign of the result.
And it will, except in the case where the value returned is Integer.MIN_VALUE.
So just return -1 rather than Integer.MIN_VALUE.

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.

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.

Reversed method arguments
The arguments to this method call seem to be in the wrong order.
For example, a call Preconditions.checkNotNull("message", message) has reserved arguments: the value to be checked is the first argument.

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

BigDecimal constructed from double that isn't represented precisely
This code creates a BigDecimal from a double value that doesn't translate well to a decimal number.
For example, one might assume that writing new BigDecimal(0.1) in Java creates a BigDecimal which is exactly equal to 0.1 (an unscaled value of 1, with a scale of 1), but it is actually equal to 0.1000000000000000055511151231257827021181583404541015625.
You probably want to use the BigDecimal.valueOf(double d) method, which uses the String representation of the double to create the BigDecimal
e.g., BigDecimal.valueOf(0.1) gives 0.1

hasNext method invokes next
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.

Collections should not contain themselves
This call to a generic collection's method would only make sense if a collection contained itself (e.g., if s.contains(s) were true).
This is unlikely to be true and would cause problems if it were true (such as the computation of the hash code resulting in infinite recursion).
It is likely that the wrong value is being passed as a parameter.

D'oh! A nonsensical method invocation
This partical method invocation doesn't make sense, for reasons that should be apparent from inspection.

Invocation of hashCode on an array
The code invokes hashCode on an array.
Calling hashCode on an array returns the same value as System.identityHashCode, and ingores the contents and length of the array.
If you need a hashCode that depends on the contents of an array a, use java.util.Arrays.hashCode(a).

Double.longBitsToDouble invoked on an 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.

Vacuous call to collections
This call doesn't make sense.
For any collection c, calling c.containsAll(c) should always be true, and c.retainAll(c) should have no effect.

Can't use reflection to check for presence of annotation without runtime retention
Unless an annotation has itself been annotated with @Retention(RetentionPolicy.RUNTIME),
the annotation can't be observed using reflection (e.g., by using the isAnnotationPresent method).

Futile attempt to change max pool size of ScheduledThreadPoolExecutor
(Javadoc) While ScheduledThreadPoolExecutor inherits from ThreadPoolExecutor, a few of the inherited tuning methods are not useful for it.
In particular, because it acts as a fixed-sized pool using corePoolSize threads and an unbounded queue, adjustments to maximumPoolSize have no useful effect.

Creation of ScheduledThreadPoolExecutor with zero core threads
(Javadoc) A ScheduledThreadPoolExecutor with zero core threads will never execute anything; changes to the max pool size are ignored.

Useless/vacuous call to EasyMock method
This call doesn't pass any objects to the EasyMock method, so the call doesn't do anything.

equals() used to compare 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[]).

Invocation of equals() on an array, which is equivalent to ==
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[]).
To compare the addresses of the arrays, it would be less confusing to explicitly check pointer equality using ==.

equals(...) used to compare incompatible arrays
This method invokes the .equals(Object o) to compare two arrays, but the arrays of of incompatible types (e.g., String[] and StringBuffer[], or String[] and int[]).
They will never be equal.
In addition, when equals(...) is used to compare arrays it only checks to see if they are the same array, and ignores the contents of the arrays.

Call to equals(null)
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.

Call to equals() comparing 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.

Call to equals() comparing different interface types
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.

Call to equals() comparing different 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.

Using pointer equality to compare different types
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.

equals method always returns 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 fundamentally, 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; }

equals method always returns 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.

equals method compares class names rather than class objects
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.

Covariant equals() method defined for enum
This class defines an enumeration, and equality on enumerations are defined using object identity.
Defining 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.

equals() method defined that doesn't override equals(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.

equals() method defined that doesn't override Object.equals(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.

equals method overrides equals in superclass and may not be 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 symmetrical (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.

Covariant equals() method defined, Object.equals(Object) inherited
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.

Doomed test for equality to NaN
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

Format string placeholder incompatible with passed argument
The format string placeholder is incompatible with the corresponding argument.
For example, System.out.println("%d\n", "hello");
The %d placeholder requires a numeric argument, but a string value is passed instead.
A runtime exception will occur when this statement is executed.

The type of a supplied argument doesn't match format specifier
One of the arguments is uncompatible with the corresponding format string specifier.
As a result, this will generate a runtime exception when executed.
For example, String.format("%d", "1") will generate an exception, since the String "1" is incompatible with the format specifier %d.

MessageFormat supplied where printf style format expected
A method is called that expects a Java printf format string and a list of arguments.
However, the format string doesn't contain any format specifiers (e.g., %s) but does contain message format elements (e.g., {0}).
It is likely that the code is supplying a MessageFormat string when a printf-style format string is required.
At runtime, all of the arguments will be ignored and the format string will be returned exactly as provided without any formatting.

More arguments are passed than are actually used in the format string
A format-string method with a variable number of arguments is called, but more arguments are passed than are actually used by the format string.
This won't cause a runtime exception, but the code may be silently omitting information that was intended to be included in the formatted string.

Illegal format string
The format string is syntactically invalid, and a runtime exception will occur when this statement is executed.

Format string references missing argument
Not enough arguments are passed to satisfy a placeholder in the format string.
A runtime exception will occur when this statement is executed.

No previous argument for format string
The format string specifies a relative index to request that the argument for the previous format specifier be reused.
However, there is no previous argument. For example,
formatter.format("%<s %s", "a", "b")
would throw a MissingFormatArgumentException when executed.

No relationship between generic parameter and method argument
This call to a generic collection method contains an argument with an incompatible class from that of the collection's parameter
(i.e., the type of the argument is neither a supertype nor a subtype of the corresponding generic type argument).
Therefore, it is unlikely that the collection contains any objects that are equal to the method argument used here.
Most likely, the wrong value is being passed to the method.
In general, instances of two unrelated classes are not equal.

For example, if the Foo and Bar classes are not related by subtyping, then an instance of Foo should not be equal to an instance of Bar.
Among other issues, doing so will likely result in an equals method that is not symmetrical.
For example, if you define the Foo class so that a Foo can be equal to a String, your equals method isn't symmetrical since a String can only be equal to a String.
In rare cases, people do define non-symmetrical equals methods and still manage to make their code work.

Although none of the APIs document or guarantee it, it is typically the case that if you check if a Collection<String> contains a Foo, the equals method of argument (e.g., the equals method of the Foo class) used to perform the equality checks.

Signature declares use of unhashable class in hashed construct
A method, field or class declares a generic signature where a non-hashable class is used in context where a hashable class is required.
A class that declares an equals method but inherits a hashCode() method from Object is unhashable, since it doesn't fulfill the requirement that equal objects have equal hashCodes.

Use of class without a hashCode() method in a hashed data structure
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.

int value converted to long and used as absolute time
This code converts a 32-bit int value to a 64-bit long value, and then passes that value for a method parameter that requires an absolute time value.
An absolute time value is the number of milliseconds since the standard base time known as "the epoch", namely January 1, 1970, 00:00:00 GMT.
For example, the following method, intended to convert seconds since the epoc into a Date, is badly broken:
Date getDate(int seconds) { return new Date(seconds * 1000); }
The multiplication is done using 32-bit arithmetic, and then converted to a 64-bit value.
When a 32-bit value is converted to 64-bits and used to express an absolute time value, only dates in December 1969 and January 1970 can be represented.
Correct implementations for the above method are:
// Fails for dates after 2037
Date getDate(int seconds) { return new Date(seconds * 1000L); }
// better, works for all dates
Date getDate(long seconds) { return new Date(seconds * 1000); }

integral value cast to double and then passed to Math.ceil
This code converts an integral value (e.g., int or long) 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.

int value cast to float and then passed to Math.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.

JUnit assertion in run method will not be noticed by JUnit
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.

TestCase declares a 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()

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

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

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

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

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

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

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

Integer multiply of result of integer remainder
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)

Bad comparison of int value with long constant
This code compares an int value with a long constant that is outside the range of values that can be represented as an int value.
This comparison is vacuous and possibility to be incorrect.

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

Bad comparison of 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

Doomed attempt to append to an 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.

A parameter is dead upon entry to a method 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.

Class defines field that masks a superclass 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.

Method defines a variable that obscures a 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.

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

Null pointer dereference in method on exception path
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.

Method does not check for null argument
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.

close() invoked on a value that is always null
close() is being invoked on a value that is always null.
If this statement is executed, a null pointer exception will occur.
But the big risk here you never close something that should be closed.

Null value is guaranteed to be dereferenced
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).
Note that a check such as if (x == null) throw new NullPointerException(); is treated as a dereference of x.

Value is null and guaranteed to be dereferenced 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).

Nonnull field is not initialized
The field is marked as nonnull, but isn't written to by the constructor.
The field might be initialized elsewhere during constructor, or might always be initialized before use.

Method call passes null to a nonnull parameter
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.

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

A known null value is checked to see if it is an instance of a type
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.

Possible null pointer dereference
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.

Possible null pointer dereference in method on exception path
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.

Method call passes null for nonnull parameter
This method call passes a null value for a nonnull method parameter.
Either the parameter is annotated as a parameter that should always be nonnull, or analysis has shown that it will always be dereferenced.

Method call passes null for nonnull parameter
A possibly-null value is passed at a call site where all known target methods require the parameter to be nonnull.
Either the parameter is annotated as a parameter that should always be nonnull, or analysis has shown that it will always be dereferenced.

Non-virtual method call passes null for nonnull parameter
A possibly-null value is passed to a nonnull method parameter.
Either the parameter is annotated as a parameter that should always be nonnull, or analysis has shown that it will always be dereferenced.

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

Read of unwritten field
The program is dereferencing a field that does not seem to ever have a non-null value written to it.
Unless the field is initialized via some mechanism not seen by the analysis, dereferencing this value will generate a null pointer exception.

Class defines equal(Object); should it be equals(Object)?
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.

Class defines hashcode(); should it be 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.

Class defines tostring(); should it be 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.

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

Very confusing method names
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.

Method doesn't override method in superclass due to wrong package for parameter
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.

Method assigns boolean literal in boolean expression
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 =.

Suspicious reference 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.
It is possible to create distinct instances that are equal but do not compare as == since they are different objects.
Examples of classes which should generally not be compared by reference are java.lang.Integer, java.lang.Float, etc.

Nullcheck of value previously dereferenced
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.

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

File.separator used for 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

"." used for regular expression
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, and s.split(".") always returns a zero length array of String.

Random value from 0 to 1 is coerced to the integer 0
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.

Bad attempt to compute absolute value of signed 32-bit 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)
One out of 2^32 strings have a hashCode of Integer.MIN_VALUE, including "polygenelubricants" "GydZG_" and ""DESIGNING WORKHOUSES".

Bad attempt to compute absolute value of signed random integer
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).
Same problem arised for long values as well

Code checks for specific values returned by compareTo
This code invoked a compareTo or compare method, and checks to see if the return value is a specific value, such as 1 or -1.
When invoking these methods, you should only check the sign of the result, not for any specific non-zero value.
While many or most compareTo and compare methods only return -1, 0 or 1, some of them will return other values.

Exception created and dropped rather than 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");

Method ignores return value
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();

Repeated conditional tests
The code contains a conditional test is performed twice, one right after the other (e.g., x == 0 || x == 0).
Perhaps the second occurrence is intended to be something else (e.g., x == 0 || y == 0).

Self assignment of field
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.

Self comparison of field with itself
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.

Nonsensical self computation involving a field (e.g., x & x)
This method performs a nonsensical computation of a field with another reference to the same field (e.g., x&x or x-x).
Because of the nature of the computation, this operation doesn't seem to make sense, and may indicate a typo or a logic error.
Double check the computation.

Self assignment of local rather than assignment to field
This method contains a self assignment of a local variable, and there is a field with an identical name.
assignment appears to have been ; e.g.
  int foo;
  public void setFoo(int foo) {
    foo = foo;
  }
The assignment is useless. Did you mean to assign to the field instead?

Self comparison of value with itself
This method compares a local variable with itself, and may indicate a typo or a logic error.
Make sure that you are comparing the right things.

Nonsensical self computation involving a variable (e.g., x & x)
This method performs a nonsensical computation of a local variable with another reference to the same variable (e.g., x&x or x-x).
Because of the nature of the computation, this operation doesn't seem to make sense, and may indicate a typo or a logic error.
Double check the computation.

Dead store due to switch statement fall through
A value stored in the previous switch case is overwritten here due to a switch fall through.
It is likely that you forgot to put a break or return at the end of the previous case.

Dead store due to switch statement fall through to throw
A value stored in the previous switch case is ignored here due to a switch fall through to a place where an exception is thrown.
It is likely that you forgot to put a break or return at the end of the previous case.

Deadly embrace of non-static inner class and thread local
This class is an inner class, but should probably be a static inner class.
As it is, there is a serious danger of a deadly embrace between the inner class and the thread local in the outer class.
Because the inner class isn't static, it retains a reference to the outer class. If the thread local contains a reference to an instance of the inner class, the inner and outer instance will both be reachable and not eligible for garbage collection.

Unnecessary type check done using instanceof operator
Type check performed using the instanceof operator where it can be statically determined whether the object is of the type requested.

Method attempts to access a prepared statement parameter with index 0
A call to a setXXX method of a prepared statement was made where the parameter index is 0.
As parameter indexes start at index 1, this is always a mistake.

Method attempts to access a result set field with index 0
A call to getXXX or updateXXX methods of a result set was made where the field index is 0.
As ResultSet fields start at index 1, this is always a mistake.

Unneeded use of currentThread() call, to call interrupted()
This method invokes the Thread.currentThread() call, just to call the interrupted() method.
As interrupted() is a static method, is more simple and clear to use Thread.interrupted().

Static Thread.interrupted() method invoked on thread instance
This method invokes the Thread.interrupted() method on a Thread object that appears to be a Thread object that is not the current thread.
As the interrupted() method is static, the interrupted method will be called on a different object than the one the author intended.

Method must be private in order for serialization to work
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.

The readResolve method must not be declared as a static method.
In order for the readResolve method to be recognized by the serialization mechanism, it must not be declared as a static method.

Value annotated as carrying a type qualifier used where a value that must not carry that qualifier is required
A value specified as carrying a type qualifier annotation is consumed in a location or locations requiring that the value not carry that annotation.
More precisely, a value annotated with a type qualifier specifying when=ALWAYS is guaranteed to reach a use or uses where the same type qualifier specifies when=NEVER.
For example, say that @NonNegative is a nickname for the type qualifier annotation @Negative(when=When.NEVER).
The following code will generate this warning because the return statement requires a @NonNegative value, but receives one that is marked as @Negative.
    public @NonNegative Integer example(@Negative Integer value) {
        return value;
    }

Comparing values with incompatible type qualifiers
A value specified as carrying a type qualifier annotation is compared with a value that doesn't ever carry that qualifier.
More precisely, a value annotated with a type qualifier specifying when=ALWAYS is compared with a value that where the same type qualifier specifies when=NEVER.
For example, say that @NonNegative is a nickname for the type qualifier annotation @Negative(when=When.NEVER)
The following code will generate this warning because the return statement requires a @NonNegative value, but receives one that is marked as @Negative.
public boolean example(@Negative Integer value1, @NonNegative Integer value2) {
        return value1.equals(value2);
}

Value that might not carry a type qualifier is always used in a way requires that type qualifier
A value that is annotated as possibility not being an instance of the values denoted by the type qualifier, and the value is guaranteed to be used in a way that requires values denoted by that type qualifier.

Value that might carry a type qualifier is always used in a way prohibits it from having that type qualifier
A value that is annotated as possibility being an instance of the values denoted by the type qualifier, and the value is guaranteed to be used in a way that prohibits values denoted by that type qualifier.

Value annotated as never carrying a type qualifier used where value carrying that qualifier is required
A value specified as not carrying a type qualifier annotation is guaranteed to be consumed in a location or locations requiring that the value does carry that annotation.
More precisely, a value annotated with a type qualifier specifying when=NEVER is guaranteed to reach a use or uses where the same type qualifier specifies when=ALWAYS.

Value without a type qualifier used where a value is required to have that qualifier
A value is being used in a way that requires the value be annotation with a type qualifier.
The type qualifier is strict, so the tool rejects any values that do not have the appropriate annotation.
To coerce a value to have a strict annotation, define an identity function where the return value is annotated with the strict annotation.
This is the only way to turn a non-annotated value into a value with a strict type qualifier annotation.

Uncallable method defined in anonymous class
This anonymous class defined a method that is not directly invoked and does not override a method in a superclass.
Since methods in other classes cannot directly invoke methods declared in an anonymous class, it seems that this method is uncallable.
The method might simply be dead code, but it is also possible that the method is intended to override a method declared in a superclass, and due to an typo or other error the method does not, in fact, override the method it is intended to.

Uninitialized read of field in constructor
This constructor reads a field which has not yet been assigned a value.
This is often caused when the programmer mistakenly uses the field instead of one of the constructor's parameters.

Uninitialized read of field method called from constructor of superclass
This method is invoked in the constructor of of the superclass.
At this point, the fields of the class have not yet initialized.
To make this more concrete, consider the following classes:
abstract class A {
  int hashCode;
  abstract Object getValue();
  A() {
    hashCode = getValue().hashCode();
    }
  }
class B extends A {
  Object value;
  B(Object v) {
    this.value = v;
    }
  Object getValue() {
    return value;
  }
  }
When a B is constructed, the constructor for the A class is invoked before the constructor for B sets value.
Thus, when the constructor for A invokes getValue, an uninitialized value is read for value

Invocation of toString on an unnamed 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.

Invocation of toString on an 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.

Array formatted in useless way using format string
One of the arguments being formatted with a format string is an array.
This will be formatted using a fairly useless format, such as [I@304282, which doesn't actually show the contents of the array.
Consider wrapping the array using Arrays.asList(...) before handling it off to a formatted.

Field only ever set to null
All writes to this field are of the constant value null, and thus all reads of the field will return null.
Check for errors, or remove it if it is useless.

Unwritten field
This field is never written.
All reads of it will return the default value.
Check for errors (should it have been initialized?), or remove it if it is useless.

Primitive array passed to function expecting a variable number of object arguments
This code passes a primitive array to a function that takes a variable number of object arguments.
This creates an array of length one to hold the primitive array and passes it to the function.

No comments:

Post a Comment

Note: only a member of this blog may post a comment.