1

It seems like a simple question but I'm wondering why if I had some String variable like this:

String name = "John";

And then I'm using the substring method like this :

System.out.print(name.substring(3,4));

it works fine but if i'd change 4 for 5 or higher I get IndexOutOfBoundsException. But as i understand indexes correct there is no 4 index as well but the outpul will be "n"

J O H N
0 1 2 3 

Could someone explain such behavior? Thanks in advance!

2
  • It has 4 as endIndex, meaning it will take the chars starting from the beginIndex (3) up to (so, exclusive) the endIndex. Commented Jan 30, 2015 at 14:26
  • Reading the documentation helps sometimes ... Commented Jan 30, 2015 at 14:28

4 Answers 4

7

The second parameter to substring is an exclusive upper bound - so it's allowed to be equal to the length of the string, in order to include the last character. Likewise it makes sense to allow the starting point to be "at" the end of the string, so long as the end is equal to the start, yielding an empty string.

Basically, for APIs which deal with ranges, it often makes sense to think of the indexes as being "between" characters rather than "on" them. For example:

  J O H N
 ^ ^ ^ ^ ^
 0 1 2 3 4

Both indexes have to be within the range shown, and the endIndex index must be either the same as beginIndex or to the right - then the substring is the characters between the two corresponding boundaries:

"JOHN".substring(1, 3) is "OH"

  J O H N
   ^ ^ ^
   1   3

This is exactly as documented, of course

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

Sign up to request clarification or add additional context in comments.

1 Comment

Nice way of thinking characters indexes!
1

From http://docs.oracle.com/javase/7/docs/api/java/lang/String.html#substring(int,%20int):

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

You string's length is 4, so 4 is OK but 5 or more is KO.

Comments

0

substring(a,b) method of String object returns substring from index a to b-1 so substring(3,4) return only "N" i.e only index value 3. note that substring(a,a) returns always a null string.

Comments

0

I think you are missunderstanding this by saying that"there is no 4 index as well but the outpul will be "n"" , the substring method counts from 1(not from 0) so your first example had nothing wrong with it because the fourth character was atually n.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.