File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes IndexOutOfBounds and StringIndexOutOfBounds Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "IndexOutOfBounds and StringIndexOutOfBounds" Watch "IndexOutOfBounds and StringIndexOutOfBounds" New topic

IndexOutOfBounds and StringIndexOutOfBounds

Sarma Lolla
Ranch Hand

Joined: Oct 21, 2002
Posts: 203
Here is what API documentations about String.subString method

public String substring(int beginIndex,
int endIndex)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. Thus the length of the substring is endIndex-beginIndex.
"hamburger".substring(4, 8) returns "urge"
"smiles".substring(1, 5) returns "mile"

beginIndex - the beginning index, inclusive.
endIndex - the ending index, exclusive.
the specified substring.

IndexOutOfBoundsException - if the beginIndex is negative, or endIndex is larger than the length of this String object, or beginIndex is larger than endIndex.

Here again API documentation about StringIndexOutOfBoundsException

public class StringIndexOutOfBoundsException
extends IndexOutOfBoundsException
Thrown by String methods to indicate that an index is either negative or greater than the size of the string. For some methods such as the charAt method, this exception also is thrown when the index is equal to the size of the string.

My question is Can there be any confusion when dealing with questions on Strings in exam?
When I execute a simple subString() with negative index for the end index I am getting StringIndexOutOfBounds instead of IndexOutOfBounds as specified by API.
[ March 03, 2003: Message edited by: Sarma Lolla ]
Rodney Woodruff
Ranch Hand

Joined: Dec 04, 2001
Posts: 80
This can be confusing. Keep in mind that StringIndexOutOfBoundsException extends IndexOutOfBoundsException. This means that StringIndexOutOfBoundsException is an IndexOutOfBoundsException.
So, to more directly answer your question, it helps to understand in the inheritance hierarchy.
For example:

would work if the code that generated the exception threw either StringIndexOutOfBoundsException or an IndexOutOfBoundsException. However, the following code:

would only catch a StringIndexOutOfBoundsException.

Hope This Helps
I agree. Here's the link:
subject: IndexOutOfBounds and StringIndexOutOfBounds
It's not a secret anymore!