KKKK
KKKK

Reputation: 347

Java String index out of bounds confusion

Suppose I have a

String temp = "abcd";

System.out.println(temp.substring(0,4)); // out of bound, no error
System.out.println(temp.substring(0,5)); // out of bound, error

Why?

Upvotes: 0

Views: 273

Answers (4)

shreshta bm
shreshta bm

Reputation: 304

The substring(0,4) does not consider 0 to 4. It considers 0 to 3. The 2nd index is always subtracted by 1. In your second case temp[4] is out of bounds.

Upvotes: 0

Atri
Atri

Reputation: 5831

According to docs:

public String substring(int beginIndex, int endIndex)

The substring begins at the specified beginIndex and extends to the character at index endIndex - 1.

IndexOutOfBoundsException - if the beginIndex is negative, or endIndex is larger than the length of this String object, or beginIndex is larger than endIndex.

Since System.out.println(temp.substring(0,5)); where 5 > length of string (abcd), hence the exception.

Upvotes: 1

rgettman
rgettman

Reputation: 178243

The Javadocs for this method state:

The substring begins at the specified beginIndex and extends to the character at index endIndex - 1.

Throws:

IndexOutOfBoundsException - if the beginIndex is negative, or endIndex is larger than the length of this String object, or beginIndex is larger than endIndex.

An end index of length is ok, but length + 1 is not.

Upvotes: 3

Frank Puffer
Frank Puffer

Reputation: 8215

Because the substring ends at endIndex-1.

Upvotes: 0

Related Questions