[java:S2440] False positive: Classes with only "static" methods should not be instantiated

Hi all,

SonarCloud reports “Remove this instantiation of String” warning for the following pieces of Java code:

public static String getDChars( byte[] block, int pos, int length )
{
    return new String( block, pos - 1, length ).trim();
}

public static String getDChars( byte[] block, int pos, int length, String encoding )
{
    try {
        return new String( block, pos - 1, length, encoding ).trim();
    }
    catch ( UnsupportedEncodingException ex ) {
        throw new RuntimeException( ex );
    }
}

It’s obvious however that standard Java String class has non-static methods, so its instantiation is absolutely legitimate.

Hi Oleg,

you’re right, S2440 should not report on String. I cannot reproduce the issue though. In the following code example, S2440 is reported for new A() only, not for new String():

class Test {
  void test(byte[] block, int pos, int length) {
    String s = new String( block, pos - 1, length ).trim();
    A a = new A();
  }
}

class A {
  static void foo() {}
}

Which SonarLint version are you using?

Does String maybe (accidentally) refer to something else than java.lang.String in your class?

Best,

Marco

Hi Marco,

it seems that this issue is now gone. We don’t have S2440 for our codebase anymore. I can’t say exactly when this problem disappeared.

1 Like