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.
About Question enthuware.ocajp.i.v7.2.968 :
Moderator: admin
-
- Posts: 22
- Joined: Wed Jan 08, 2014 11:24 am
- Contact:
-
- Site Admin
- Posts: 10066
- Joined: Fri Sep 10, 2010 9:26 pm
- Contact:
Re: About Question enthuware.ocajp.i.v7.2.968 :
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.
If you like our products and services, please help us by posting your review here.
-
- Posts: 9
- Joined: Mon Apr 28, 2014 9:16 am
- Contact:
Re: About Question enthuware.ocajp.i.v7.2.968 :
The last line where"emptiness".substring(9) returns "" (an empty string)
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."emptiness".substring(9) returns ""
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.
-
- Site Admin
- Posts: 10066
- Joined: Fri Sep 10, 2010 9:26 pm
- Contact:
Re: About Question enthuware.ocajp.i.v7.2.968 :
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.
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.
If you like our products and services, please help us by posting your review here.
-
- Posts: 60
- Joined: Thu Apr 15, 2021 12:21 pm
- Contact:
Re: About Question enthuware.ocajp.i.v7.2.968 :
@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
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
Who is online
Users browsing this forum: No registered users and 155 guests