Page 1 of 1

About Question enthuware.ocajp.i.v7.2.968 :

Posted: Tue Jan 28, 2014 6:37 pm
by JeramieH
Just out of curiosity, why was (endIndex-1) chosen as the behavior in Java? Surely there must be some common use case where this choice makes sense, but it's always struck me as awkward to remember. Why would I want to count one past where I wanted to stop, just so Java can then fall back by one?

Likewise, having trouble remembering which functions use endIndex (like Strings) while others use length (like System.arraycopy). It's functionally the same fact being expressed.

Re: About Question enthuware.ocajp.i.v7.2.968 :

Posted: Tue Jan 28, 2014 9:25 pm
by admin
This is just a convention that has been followed for long. Some other languages also use the same. Since Java evolved from c/c++ world, it follows the same convention.

Re: About Question enthuware.ocajp.i.v7.2.968 :

Posted: Tue May 20, 2014 9:34 am
by UmairAhmed
"emptiness".substring(9) returns "" (an empty string)
The last line where
"emptiness".substring(9) returns ""
said that it return the empty string. Isn't it return the exception as we are the trying to access the 10th element actually in the provided string where as "emptiness" has only 9 elements.

P.S : I know it compiles and works as its said in explanation but just wondering why it is not giving the String index out of bound exception. How come, the 10th element could be access through substring method.

Re: About Question enthuware.ocajp.i.v7.2.968 :

Posted: Tue May 20, 2014 10:49 am
by admin
There is no special reason. It is how they have defined this method. If you look at the API description here: http://docs.oracle.com/javase/7/docs/ap ... tring(int)
It says: IndexOutOfBoundsException - if beginIndex is negative or larger than the length of this String object.

In this case, since the length of the string is 9, there is no exception.

Re: About Question enthuware.ocajp.i.v7.2.968 :

Posted: Sat Jul 24, 2021 4:47 am
by enthunoob
@JeramieH
Cause for ALL methods that require a begin- and end index the convention is:
- Begin index = inclusive
- End index = exclusive

Length or size isn't an index