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

Versions used

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

Minimal code sample to reproduce

public String getZipCode4()
{
	String l_zip_code = getZipCode();
	
	if ( l_zip_code.length() <= 5 )
	{
		return PRJ_NULL_STRING;
	}
	
	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.

Cheers,
Yassin

6 Likes

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!

3 Likes