The substring method in the String class reaches an index that is not expected

Sorry if the title is not clear.

Now in the rows the index starts at 0. So, for example:

Index    0   1   2   3   4
String   H   E   L   L   O

In this case, the last index is 4.

If I try to do something like this:

System.out.println("hello".charAt(5));

He would throw an “Index Out Of Bounds Exception,” as it should.

However, if I try to run the following code:

System.out.println("hello".substring(5));

He works! I wrote a similar code, noticed this later and could not understand.

After all, the question is, as far as possible, we can achieve this index, shouldn't we? This allows us to write:

stringObj.substring(stringObj.length());

and that doesn’t look very safe, since stringObj.length () returns us an integer that is larger than the last index.

? , , ?

+5
4

substring , , (, )

         H E L L O
        0 1 2 3 4 5    <- acceptable range of indexes for "HELLO"
        ^         ^
        |         |
      start      end = length
   (min index) (max index)

start end .

"HELLO".substring(2,4)

 L L 
2 3 4

"LL".

substring(5) , substring(5,length), substring(5,5). , 5 "" , 5 5 , .

substring(0,0) substring(1,1) .., .

StringIndexOutOfBoundsException , , :

  • : -1, -2,...
  • length. : 6 7,...
+10

- "Index Out Of Bounds Exception",

. Exception Execution.

System.out.println("hello".substring(5));

, , , , , ?

API substring(...). , .

.

+3

Java String API (http://docs.oracle.com/javase/7/docs/api/java/lang/String.html#substring(int))

String ".length()" .

"HELLO" 0- > 4, 5 (), , "Hello".length().

, (Stringobj.length() - 1); String Array .length() .size() Java.

+1

charAt .

charAt, , , :

, String. .

:

System.out.println("hello".charAt(5));

Exception in thread "main" java.lang.StringIndexOutOfBoundsException:
String index out of range: 5

, , 4.

substringdescribed in the java documentation and explains your exact situation here in the Examples section, which says that:

void .substring (9) returns "" (empty string)

For further reference, here is the source code for javasubstring(int index) , where you can see that it uses the java method substring(int beginInndex, int endIndex).

0
source

Source: https://habr.com/ru/post/1614976/


All Articles