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

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

Moderator: admin

Post Reply
troydh53
Posts: 5
Joined: Fri Sep 11, 2015 8:06 am
Contact:

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

Post by troydh53 »

The explanation says: "emptiness".substring(9) returns "" (an empty string). And that's correct. I would have expected an error because there are only 8 elements to the string. Why doesn't it throw a StringIndexOutOfBounds error?

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

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

Post by admin »

Because of the way substring method has been designed. As per its JavaDoc API, it throws an IndexOutOfBoundsException only if beginIndex is negative or larger than the length of this String object. The length of the given string is 9. So substring(9) will not throw an exception.

There is no special reason here. It is just the way they designed this method to work.

HTH,
Paul.
If you like our products and services, please help us by posting your review here.

deniscapeto
Posts: 6
Joined: Wed Dec 02, 2015 5:50 pm
Contact:

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

Post by deniscapeto »

why does the StringBuilder sb is modified by "blooperper".delete(3, 5) if the code ignored the return?

the correct answer wouldn´t be "blooperper"?

or the code could be:

sb = sb.append(s.substring(4)).delete(3, 5);

StringBuilder isn´t immutable like String?

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

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

Post by admin »

No, StringBuilder (and StringBuffer) is not immutable.
I am not sure why you feel that the code ignoring the return value is important. The StringBuilder object on which you called delete(3,5) has already been changed by the delete method. The method returns the reference to the same StringBuilder object (which has now been changed internally). Now, whether you use the return value or not is immaterial.

HTH,
Paul.
If you like our products and services, please help us by posting your review here.

deniscapeto
Posts: 6
Joined: Wed Dec 02, 2015 5:50 pm
Contact:

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

Post by deniscapeto »

Thanks Paul,

I thought delete method on StringBuilder worked like String, so the return would be important. Now it´s clarified.

Post Reply

Who is online

Users browsing this forum: No registered users and 45 guests