# Use Offset Based String Methods

# 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) (opens new window) is followed by startsWith(aString) (opens new window), then both invocations are removed and startsWith(aString, beginIndex) (opens new window) is used instead.

# Benefits

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

# Tags

# 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);

🛠️ Auto-refactor Available

You can auto-refactor this with jSparrow.
Drop this button to your Eclipse IDE workspace to install jSparrow for free:

Drag to your running Eclipse* workspace. *Requires Eclipse Marketplace Client

Need help? Check out our installation guide.

# Properties

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