0

I am new to JAVA programming and currently doing some practice code via a website, I would like some clarity on below

given:

String str = "Jason";
str.substring(4,5);

result = "n"

Question: Method substring parameters are (begin_index, end_index). but there is no index of 5 for variable str . does JAVA automatically -1 when it comes to the length method of a string?

tobias_k
  • 81,265
  • 12
  • 120
  • 179
  • 4
    You might want to rename your question. What you're asking has nothing to do with an else clause or conditional logic of any kind. – azurefrog Jun 10 '15 at 20:32

3 Answers3

5

The substring() method is "inclusive exclusive".

This means that in Jason, when you provided (4, 5) as parameters, it's inclusive of index 4 (n), but exclusive of index 5. Index 5 doesn't exist, but it's exclusive so it's okay.

Note that .length is NOT zero indexed. If you try to get the .length you'll get a 5. String character positions ARE zero indexed. So Jason indexed would have 0 on J and 4 on N, even though the length is 5.

Aify
  • 3,543
  • 3
  • 24
  • 43
1

See the API documentation of substring(int beginIndex, int endIndex)

Parameters:

beginIndex - the beginning index, inclusive.

endIndex - the ending index, exclusive.

So, what it does is take the characters in the string starting at beginIndex up to, but excluding, endIndex.

This is actually a common way to do this. An advantage of taking the begin index inclusive and the end index exclusive is that it's easy to calculate the length of the substring - it's endIndex - beginIndex, and you don't have to think about adding or subtracting 1 for inclusive / exclusive.

Jesper
  • 202,709
  • 46
  • 318
  • 350
0

Quoting from Oracle Documentation http://docs.oracle.com/javase/7/docs/api/java/lang/String.html#substring%28int,%20int%29 :

Returns a new string that is a substring of this string. The substring begins at the specified beginIndex and extends to the character at index endIndex - 1.

JohnMarco
  • 31
  • 1
  • 5