False positive: squid:S3039 "String" calls should not go beyond their bounds

Versions used

  • SonarQube: 7.9.1
  • Scanner: (Ant)
  • Language analyzer: SonarJava

Minimal code sample to reproduce

public String getZipCode4()
	String l_zip_code = getZipCode();
	if ( l_zip_code.length() <= 5 )
	if ( l_zip_code.length() > 9 )
		// FP: Refactor this "substring" call; it will result in an "StringIndexOutOfBounds" exception at runtime.
		// The if condition verifies the string is at least 10 characters long, which means a substring(5, 4) should always work
		return l_zip_code.substring( 5, 4 );

	return l_zip_code.substring( 5 );

Hello Matthew,

Welcome to our community!

I regret to say that you are wrong on this one. The Javadoc says that substring throws IndexOutOfBoundsException if beginIndex is greater than endIndex, which happens to be the case with your code given than 5 is greater than 4.

In any cases, we thank you for your contribution.



Haha, sorry! Thank you for your quick reply. I’m a C# developer primarily, where the second parameter of substring is length, if this doesn’t make that clear :p. I’ll let the Java team who wrote this code know. Win for SonarQube!