Search code examples
javaimplicit-conversion

Find integer overflows caused by Java's unintentional implicit narrowing conversions


I have code that looks like this:

public class Foo {
    public static void doStuff() {
        int x;
        /* snip */
        x += Bar.getY();
        /* snip */
    }
}

public class Bar {
    public static int getY() {
        /* snip */
    }
}

I need to change Bar.getY() to return long instead of int. Due to Java's implicit conversion with +=, doStuff will continue to compile without errors or warnings, but will now contain an integer overflow bug. Is there any way to find all instances of this sort of implicit conversion in a Java codebase, to avoid unintentionally causing this sort of bug?


Solution

  • Google's code analyzer Error Prone has a rule for narrowing compound assignments: https://github.com/google/error-prone/blob/master/docs/bugpattern/NarrowingCompoundAssignment.md