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

Help and support on OCA OCP Java Programmer Certification Questions
1Z0-808, 1Z0-809, 1Z0-815, 1Z0-816, 1Z0-817

Moderator: admin

Post Reply
JeramieH
Posts: 22
Joined: Wed Jan 08, 2014 11:24 am
Contact:

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

Post 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.

admin
Site Admin
Posts: 10036
Joined: Fri Sep 10, 2010 9:26 pm
Contact:

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

Post 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.
If you like our products and services, please help us by posting your review here.

UmairAhmed
Posts: 9
Joined: Mon Apr 28, 2014 9:16 am
Contact:

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

Post 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.

admin
Site Admin
Posts: 10036
Joined: Fri Sep 10, 2010 9:26 pm
Contact:

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

Post 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.
If you like our products and services, please help us by posting your review here.

enthunoob
Posts: 60
Joined: Thu Apr 15, 2021 12:21 pm
Contact:

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

Post 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

Post Reply

Who is online

Users browsing this forum: marpiva and 38 guests