Bug patterns

This list is auto-generated from our sources. Each bug pattern includes code examples of both positive and negative cases; these examples are used in our regression test suite.

Patterns which are marked Experimental will not be evaluated against your code, unless you specifically configure Error Prone. The default checks are marked On by default, and each release promotes some experimental checks after we’ve vetted them against Google’s codebase.

On by default : ERROR

AndroidInjectionBeforeSuper
AndroidInjection.inject() should always be invoked before calling super.lifecycleMethod()

ArrayEquals
Reference equality used to compare arrays

ArrayHashCode
hashcode method on array does not hash array contents

ArrayToString
Calling toString on an array does not provide useful information

ArraysAsListPrimitiveArray
Arrays.asList does not autobox primitive arrays, as one might expect.

AsyncCallableReturnsNull
AsyncCallable should not return a null Future, only a Future whose result is null.

AsyncFunctionReturnsNull
AsyncFunction should not return a null Future, only a Future whose result is null.

BadShiftAmount
Shift by an amount that is out of range

BundleDeserializationCast
Object serialized in Bundle may have been flattened to base type.

ChainingConstructorIgnoresParameter
The called constructor accepts a parameter with the same name and type as one of its caller's parameters, but its caller doesn't pass that parameter to it. It's likely that it was intended to.

CheckReturnValue
Ignored return value of method that is annotated with @CheckReturnValue

CollectionIncompatibleType
Incompatible type as argument to Object-accepting Java collections method

ComparisonOutOfRange
Comparison to value that is out of range for the compared type

CompatibleWithAnnotationMisuse
@CompatibleWith's value is not a type argument.

CompileTimeConstant
Non-compile-time constant expression passed to parameter with @CompileTimeConstant type annotation.

ConstantOverflow
Compile-time constant expression overflows

DaggerProvidesNull
Dagger @Provides methods may not return null unless annotated with @Nullable

DeadException
Exception created but not thrown

DoNotCall
This method should not be called.

EqualsNaN
== NaN always returns false; use the isNaN methods instead

FallThrough
Switch case may fall through

FilesLinesLeak
The stream returned by Files.lines should be closed using try-with-resources

ForOverride
Method annotated @ForOverride must be protected or package-private and only invoked from declaring class, or from an override of the method

FormatString
Invalid printf-style format string

FormatStringAnnotation
Invalid format string passed to formatting method.

FunctionalInterfaceMethodChanged
Casting a lambda to this @FunctionalInterface can cause a behavior change from casting to a functional superinterface, which is surprising to users. Prefer decorator methods to this surprising behavior.

FuturesGetCheckedIllegalExceptionType
Futures.getChecked requires a checked exception type with a standard constructor.

GetClassOnAnnotation
Calling getClass() on an annotation may return a proxy class

GetClassOnClass
Calling getClass() on an object of type Class returns the Class object for java.lang.Class; you probably meant to operate on the object directly

GuardedBy
Checks for unguarded accesses to fields and methods with @GuardedBy annotations

GuiceAssistedInjectScoping
Scope annotation on implementation class of AssistedInject factory is not allowed

GuiceAssistedParameters
A constructor cannot have two @Assisted parameters of the same type unless they are disambiguated with named @Assisted annotations.

GuiceInjectOnFinalField
Although Guice allows injecting final fields, doing so is disallowed because the injected value may not be visible to other threads.

HashtableContains
contains() is a legacy method that is equivalent to containsValue()

IdentityBinaryExpression
A binary expression where both operands are the same is usually incorrect.

Immutable
Type declaration annotated with @Immutable is not immutable

ImmutableModification
Modifying an immutable collection is guaranteed to throw an exception and leave the collection unmodified

IncompatibleArgumentType
Passing argument to a generic method with an incompatible type.

IndexOfChar
The first argument to indexOf is a Unicode code point, and the second is the index to start the search from

InfiniteRecursion
This method always recurses, and will cause a StackOverflowError

InjectMoreThanOneScopeAnnotationOnClass
A class can be annotated with at most one scope annotation.

InvalidPatternSyntax
Invalid syntax used for a regular expression

InvalidTimeZoneID
Invalid time zone identifier. TimeZone.getTimeZone(String) will silently return GMT instead of the time zone you intended.

IsInstanceOfClass
The argument to Class#isInstance(Object) should not be a Class

IsLoggableTagLength
Log tag too long, cannot exceed 23 characters.

JUnit3TestNotRun
Test method will not be run; please prefix name with "test"

JUnit4SetUpNotRun
setUp() method will not be run; Please add a @Before annotation

JUnit4TearDownNotRun
tearDown() method will not be run; Please add an @After annotation

JUnit4TestNotRun
Test method will not be run; please add @Test annotation

JUnitAssertSameCheck
An object is tested for reference equality to itself using JUnit library.

JavaxInjectOnAbstractMethod
Abstract and default methods are not injectable with javax.inject.Inject

LiteByteStringUtf8
This pattern will silently corrupt certain byte sequences from the serialized protocol message. Use ByteString or byte[] directly

LoopConditionChecker
Loop condition is never modified in loop body.

MislabeledAndroidString
Certain resources in android.R.string have names that do not match their content

MissingCasesInEnumSwitch
Switches on enum types should either handle all values, or have a default case.

MisusedWeekYear
Use of "YYYY" (week year) in a date pattern without "ww" (week in year). You probably meant to use "yyyy" (year) instead.

MockitoCast
A bug in Mockito will cause this test to fail at runtime with a ClassCastException

MockitoUsage
Missing method call for verify(mock) here

ModifyingCollectionWithItself
Using a collection function with itself as the argument.

MoreThanOneInjectableConstructor
This class has more than one @Inject-annotated constructor. Please remove the @Inject annotation from all but one of them.

MustBeClosedChecker
Invocations of methods or constructors annotated with @MustBeClosed must occur within the resource variable initializer of a try-with-resources statement, or the return statement of another method annotated with @MustBeClosed.

NonCanonicalStaticImport
Static import of type uses non-canonical name

NonFinalCompileTimeConstant
@CompileTimeConstant parameters should be final or effectively final

OptionalEquality
Comparison using reference equality instead of value equality

OverlappingQualifierAndScopeAnnotation
Annotations cannot be both Scope annotations and Qualifier annotations: this causes confusion when trying to use them.

Overrides
Varargs doesn't agree for overridden method

OverridesJavaxInjectableMethod
This method is not annotated with @Inject, but it overrides a method that is annotated with @javax.inject.Inject. The method will not be Injected.

PackageInfo
Declaring types inside package-info.java files is very bad form

PreconditionsCheckNotNull
Literal passed as first argument to Preconditions.checkNotNull() can never be null

PreconditionsCheckNotNullPrimitive
First argument to Preconditions.checkNotNull() is a primitive rather than an object reference

ProtoFieldNullComparison
Protobuf fields cannot be null

ProvidesMethodOutsideOfModule
@Provides methods need to be declared in a Module to have any effect.

RandomModInteger
Use Random.nextInt(int). Random.nextInt() % n can have negative results

RectIntersectReturnValueIgnored
Return value of android.graphics.Rect.intersect() must be checked

RestrictedApiChecker
Check for non-whitelisted callers to RestrictedApiChecker.

ReturnValueIgnored
Return value of this method must be used

SelfAssignment
Variable assigned to itself

SelfComparison
An object is compared to itself

SelfEquals
Testing an object for equality with itself will always be true.

SizeGreaterThanOrEqualsZero
Comparison of a size >= 0 is always true, did you intend to check for non-emptiness?

StreamToString
Calling toString on a Stream does not provide useful information

StringBuilderInitWithChar
StringBuilder does not have a char constructor; this invokes the int constructor.

SuppressWarningsDeprecated
Suppressing "deprecated" is probably a typo for "deprecation"

ThrowIfUncheckedKnownChecked
throwIfUnchecked(knownCheckedException) is a no-op.

ThrowNull
Throwing 'null' always results in a NullPointerException being thrown.

TruthSelfEquals
isEqualTo should not be used to test an object for equality with itself; the assertion will never fail.

TryFailThrowable
Catching Throwable/Error masks failures from fail() or assert*() in the try block

TypeParameterQualifier
Type parameter used as type qualifier

UnnecessaryTypeArgument
Non-generic methods should not be invoked with type arguments

UnusedAnonymousClass
Instance created but never used

UnusedCollectionModifiedInPlace
Collection is modified in place, but the result is not used

On by default : WARNING

AmbiguousMethodReference
Method reference is ambiguous

BadAnnotationImplementation
Classes that implement Annotation must override equals and hashCode. Consider using AutoAnnotation instead of implementing Annotation by hand.

BadComparable
Possible sign flip from narrowing conversion

BoxedPrimitiveConstructor
valueOf or autoboxing provides better time and space performance

CannotMockFinalClass
Mockito cannot mock final classes

ClassCanBeStatic
Inner class is non-static but does not reference enclosing class

ClassNewInstance
Class.newInstance() bypasses exception checking; prefer getDeclaredConstructor().newInstance()

DefaultCharset
Implicit use of the platform default charset, which can result in e.g. non-ASCII characters being silently replaced with '?' in many environments

DoubleCheckedLocking
Double-checked locking on non-volatile fields is unsafe

ElementsCountedInLoop
This code, which counts elements using a loop, can be replaced by a simpler library method

EqualsHashCode
Classes that override equals should also override hashCode.

EqualsIncompatibleType
An equality test between objects with incompatible types always returns false

Finally
If you return or throw from a finally, then values returned or thrown from the try-catch block will be ignored. Consider using try-with-resources instead.

FloatingPointLiteralPrecision
Floating point literal loses precision

FragmentInjection
Classes extending PreferenceActivity must implement isValidFragment such that it does not unconditionally return true to prevent vulnerability to fragment injection attacks.

FragmentNotInstantiable
Subclasses of Fragment must be instantiable via Class#newInstance(): the class must be public, static and have a public nullary constructor

FunctionalInterfaceClash
Overloads will be ambiguous when passing lambda arguments

FutureReturnValueIgnored
Return value of methods returning Future must be checked.

GetClassOnEnum
Calling getClass() on an enum may return a subclass of the enum type

ImmutableAnnotationChecker
Annotations should always be immutable

ImmutableEnumChecker
Enums should always be immutable

IncompatibleModifiers
This annotation has incompatible modifiers as specified by its @IncompatibleModifiers annotation

InjectOnConstructorOfAbstractClass
Constructors on abstract classes are never directly @Injected, only the constructors of their subclasses can be @Inject'ed.

InputStreamSlowMultibyteRead
Please also override int read(byte[], int, int), otherwise multi-byte reads from this input stream are likely to be slow.

IterableAndIterator
Class should not implement both Iterable and Iterator

JUnit3FloatingPointComparisonWithoutDelta
Floating-point comparison without error tolerance

JUnitAmbiguousTestClass
Test class inherits from JUnit 3's TestCase but has JUnit 4 @Test annotations.

LiteralClassName
Using Class.forName is unnecessary if the class is available at compile-time.

MissingFail
Not calling fail() when expecting an exception masks bugs

MissingOverride
method overrides method in supertype; expected @Override

MutableConstantField
Constant field declarations should use the immutable type (such as ImmutableList) instead of the general collection interface type (such as List)

NarrowingCompoundAssignment
Compound assignments to bytes, shorts, chars, and floats hide dangerous casts

NonAtomicVolatileUpdate
This update of a volatile variable is non-atomic

NonOverridingEquals
equals method doesn't override Object.equals

NullableConstructor
Constructors should not be annotated with @Nullable since they cannot return null

NullablePrimitive
@Nullable should not be used for primitive types since they cannot be null

NullableVoid
void-returning methods should not be annotated with @Nullable, since they cannot return null

OperatorPrecedence
Use grouping parenthesis to make the operator precedence explicit

OverridesGuiceInjectableMethod
This method is not annotated with @Inject, but it overrides a method that is annotated with @com.google.inject.Inject. Guice will inject this method, and it is recommended to annotate it explicitly.

PreconditionsInvalidPlaceholder
Preconditions only accepts the %s placeholder in error message strings

ProtoFieldPreconditionsCheckNotNull
Protobuf fields cannot be null, so this check is redundant

ProtocolBufferOrdinal
ordinal() value of Protocol Buffer Enum can change if enumeration order is changed

ReferenceEquality
Comparison using reference equality instead of value equality

RequiredModifiers
This annotation is missing required modifiers as specified by its @RequiredModifiers annotation

ShortCircuitBoolean
Prefer the short-circuiting boolean operators && and || to & and |.

SimpleDateFormatConstant
SimpleDateFormat is not thread-safe, and should not be used as a constant field.

StaticGuardedByInstance
Writes to static fields should not be guarded by instance locks

SynchronizeOnNonFinalField
Synchronizing on non-final fields is not safe: if the field is ever updated, different threads may end up locking on different objects.

TruthConstantAsserts
Truth Library assert is called on a constant.

TypeParameterShadowing
Type parameter declaration overrides another type parameter already declared

TypeParameterUnusedInFormals
Declaring a type parameter that is only used in the return type is a misuse of generics: operations on the type parameter are unchecked, it hides unsafe casts at invocations of the method, and it interacts badly with method overload resolution.

URLEqualsHashCode
Creation of a Set/HashSet/HashMap of java.net.URL. equals() and hashCode() of java.net.URL class make blocking internet connections.

UnsynchronizedOverridesSynchronized
Unsynchronized method overrides a synchronized method.

WaitNotInLoop
Because of spurious wakeups, Object.wait() and Condition.await() must always be called in a loop

Experimental : ERROR

ArgumentParameterSwap
An argument is more similar to a different parameter; the arguments may have been swapped.

AssistedInjectAndInjectOnSameConstructor
@AssistedInject and @Inject cannot be used on the same constructor.

AutoFactoryAtInject
@AutoFactory and @Inject should not be used in the same type.

ClassName
The source file name should match the name of the top-level class it contains

ComparisonContractViolated
This comparison method violates the contract

DepAnn
Deprecated item is not annotated with @Deprecated

DivZero
Division by integer literal zero

EmptyIf
Empty statement after if

InjectInvalidTargetingOnScopingAnnotation
A scoping annotation's Target should include TYPE and METHOD.

InjectMoreThanOneQualifier
Using more than one qualifier annotation on the same element is not allowed.

InjectScopeAnnotationOnInterfaceOrAbstractClass
Scope annotation on an interface or abstact class is not allowed

InjectScopeOrQualifierAnnotationRetention
Scoping and qualifier annotations must have runtime retention.

InjectedConstructorAnnotations
Injected constructors cannot be optional nor have binding annotations

InsecureCryptoUsage
A standard cryptographic operation is used in a mode that is prone to vulnerabilities

JMockTestWithoutRunWithOrRuleAnnotation
jMock tests must have a @RunWith(JMock.class) annotation, or the Mockery field must have a @Rule JUnit annotation

JavaxInjectOnFinalField
@javax.inject.Inject cannot be put on a final field.

LockMethodChecker
This method does not acquire the locks specified by its @LockMethod annotation

LongLiteralLowerCaseSuffix
Prefer 'L' to 'l' for the suffix to long literals

NoAllocation
@NoAllocation was specified on this method, but something was found that would trigger an allocation

NonRuntimeAnnotation
Calling getAnnotation on an annotation that is not retained at runtime.

NumericEquality
Numeric comparison using reference equality instead of value equality

ParameterPackage
Method parameter has wrong package

ProtoStringFieldReferenceEquality
Comparing protobuf fields of type String using reference equality

QualifierOnMethodWithoutProvides
Qualifier applied to a method that isn't a @Provides method. This method won't be used for dependency injection

StaticOrDefaultInterfaceMethod
Static and default methods in interfaces are not allowed in android builds.

UnlockMethod
This method does not acquire the locks specified by its @UnlockMethod annotation

Experimental : WARNING

ArgumentParameterMismatch
A different potential argument is more similar to the name of the parameter than the existing argument; this may be an error

AssertFalse
Assertions may be disabled at runtime and do not guarantee that execution will halt here; consider throwing an exception instead

AssistedInjectAndInjectOnConstructors
@AssistedInject and @Inject should not be used on different constructors in the same class.

BigDecimalLiteralDouble
BigDecimal(double) and BigDecimal.valueOf(double) may lose precision, prefer BigDecimal(String) or BigDecimal(long)

BindingToUnqualifiedCommonType
This code declares a binding for a common value type without a Qualifier annotation.

EmptyTopLevelDeclaration
Empty top-level type declaration

ExpectedExceptionChecker
Calls to ExpectedException#expect should always be followed by exactly one statement.

HardCodedSdCardPath
Hardcoded reference to /sdcard

MissingDefault
The Google Java Style Guide requires that each switch statement includes a default statement group, even if it contains no code. (This requirement is lifted for any switch statement that covers all values of an enum.)

NonCanonicalStaticMemberImport
Static import of member uses non-canonical name

PrimitiveArrayPassedToVarargsMethod
Passing a primitive array to a varargs method is usually wrong

QualifierWithTypeUse
Injection frameworks currently don't understand Qualifiers in TYPE_PARAMETER or TYPE_USE contexts.

RedundantThrows
Thrown exception is a subtype of another

StaticQualifiedUsingExpression
A static variable or method should be qualified with a class name, not expression

StringEquality
String comparison using reference equality instead of value equality

TestExceptionChecker
Using @Test(expected=…) is discouraged, since the test will pass if any statement in the test method throws the expected exception

UnnecessaryDefaultInEnumSwitch
Switch handles all enum values; an explicit default case is unnecessary and defeats error checking for non-exhaustive switches.

Var
Non-constant variable missing @Var annotation

Experimental : SUGGESTION

ConstantField
Field name is CONSTANT_CASE, but field is not static and final

EmptySetMultibindingContributions
@Multibinds is a more efficient and declarative mechanism for ensuring that a set multibinding is present in the graph.

FieldMissingNullable
Fields that can be null should be annotated @Nullable

MethodCanBeStatic
A private method that does not reference the enclosing instance can be static

MixedArrayDimensions
C-style array declarations should not be used

MultiVariableDeclaration
Variable declarations should declare only one variable

MultipleTopLevelClasses
Source files should not contain multiple top-level class declarations

PackageLocation
Package names should match the directory they are declared in

ParameterNotNullable
Method parameters that aren't checked for null shouldn't be annotated @Nullable

PrivateConstructorForNoninstantiableModuleTest
Add a private constructor to modules that will not be instantiated by Dagger.

PrivateConstructorForUtilityClass
Utility classes (only static members) are not designed to be instantiated and should be made noninstantiable with a default constructor.

RemoveUnusedImports
Unused imports

ReturnMissingNullable
Methods that can return null should be annotated @Nullable

ThrowsUncheckedException
Unchecked exceptions do not need to be declared in the method signature.

UnnecessaryStaticImport
Using static imports for types is unnecessary

UseBinds
@Binds is a more efficient and declarative mechanism for delegating a binding.

WildcardImport
Wildcard imports, static or otherwise, should not be used