# Use Offset Based String Methods

# Properties

Property Value
Rule ID UseOffsetBasedStringMethods
First seen in jSparrow version 3.21.0
Minimum Java version 1.1
Remediation cost 5 min
Links

# Description

This rule avoids creating intermediate String instances by making use of the overloaded offset based methods in the String API. For example, if substring(beginIndex) is followed by startsWith(aString), then both invocations are removed and startsWith(aString, beginIndex) is used instead.

# Benefits

Reduces the number of String objects whose sole purpose is to indicate an offset.

# Code Changes

# Using String startsWith

Pre

String str = "Hello World!";
boolean startsWith = str.substring(6).startsWith("World");

Post

String str = "Hello World!";
boolean startsWith = str.startsWith("World", 6);

# Using String indexOf

Pre

String str = "Hello World!";
int index = str.substring(6).indexOf("d");

Post

String str = "Hello World!";
int index = Math.max(str.indexOf("d", 6) - 6, -1);

# Using String lastIndexOf

Pre

String str = "Hello World!";
int index = str.substring(6).lastIndexOf("d");

Post

String str = "Hello World!";
int index = Math.max(str.lastIndexOf("d", 6) - 6, -1);

Automatic Application of This Rule

The automatic application of this rule is supported in the following jSparrow version:

# Tags

1
default
You & jSparrow
default

Hey there! May I help you? 😊