简体   繁体   中英

Why IndexOutOfBoundsException was not thrown when I used java substring(int beginIndex, int endIndex) even my arguments were out of bounds?

When I was trying the substring() method I found that java didn't throw IndexOutOfBoundsException in this code even though the endIndex is out of bounds

String str1 = "abcdefg";
System.out.println(str1.substring(3,7));

When I changed the endIndex to 8 then java throwed IndexOutOfBoundsException in this code

String str1 = "abcdefg";
System.out.println(str1.substring(3,8));

I already read the documentation about this form of substring https://docs.oracle.com/javase/8/docs/api/java/lang/String.html#substring-int-int-

I just remembered that in other programming language like C there is a character String called null-terminated String that is added at the end of the String here are some of my references https://en.wikipedia.org/wiki/Null-terminated_string https://www.tutorialspoint.com/cprogramming/c_strings.htm

So, I'm just wondering, does java add a null-terminated String at the end of a string that's why this code fragment "System.out.println(str1.substring(3,7));" didn't throw IndexOutOfBoundsException?

This is because the substring(start, end) function specifies an inclusive start and an exclusive end index.

This way, you can specify an index that's 1 greater than the max index to indicate that you want to go all the way to the end of the string (although, in that case, you should probably just use the single-argument substring(start) that automatically grabs to the end of the string).

This is useful if you're programmatically calling the substring(start, end) function w/ computed start and end values without having to check for the size of the string and invoking the single-argument version.

From the documentation you linked to:

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

So str1.substring(3,7) is actually taking a substring from index 3 through index 6.

What was stated in the other 2 solutions is correct. When you do:

String str1 = "abcdefg";
System.out.println(str1.substring(3,7));

This is what happens:

          v        v
[a][b][c][d][e][f][g]          --- return "defg"   
[0][1][2][3][4][5][6][7]       --- Grabbing index 3 to 6

It is reading from index 3 to 6 because the substring reads 1 character before the stated end-index.


However, when you do this:

String str1 = "abcdefg";
System.out.println(str1.substring(3,8));

This is what happens:

          v           v
[a][b][c][d][e][f][g]          --- out of bounds, trying to read after last character   
[0][1][2][3][4][5][6][7]       --- Grabbing index 3 to 7

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM