Skip to Main Content

New to Java

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

substring may be null, then what?

807601May 7 2008 — edited May 7 2008
I want to view only the first 5 characters of a string.
The string variable may be empty.

Here are the two ways I've tried to do this:
ctyCd is a string variable up to 25 characters long.
ONE:
if (ctyCd.equals(" "))
{
ctyCd = ctyCd.substring(0, 0);
}
else
{
ctyCd = ctyCd.substring(0, 5);
}

TWO:
if (ctyCd != null)
{
ctyCd = ctyCd.substring(0, 5);
}

Both ways reflect the same out of bound error:
java.lang.StringIndexOutOfBoundsException: String index out of range: 5

Thanks for any help.
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Jun 4 2008
Added on May 7 2008
6 comments
1,112 views