Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range:

softwarelovas
softwarelovas used Ask the Experts™
on
Why do I receive a out of bounds error when using substring?

String timestamp= line.substring(1, 10);

Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String ind
ex out of range:

How can I avoid this, I need to somehow check the position for null with out the thing blowing up.
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Top Expert 2016

Commented:
How can I check for null in a file while using substring?
It's not possible to get null from a file.

But in any case, the exception you cite is something quite different - an indexing problem. You're making assumptions about the value of 'line' that are incorrect. You might as well check if 'line' is null though i don't see how it could be, but more importantly, you need to check your assumption about its content, probably by at least checking its length

if (line != null && line.length() >= 11) {
  // Do it, but don't use the magic number like i just used
}

Open in new window

Author

Commented:
Hmm.. I believe what I need to do is determine why I am receiving a out of bounds error.
Post the FULL stack trace error here. If you don’t fancy that, then look for the bounds error int in the error trace, and compare it to the length of your substring term.
Information Technology Specialist
Commented:
What is the value of line and how is that determined? What are you trying to do with the substring? Remember that indexes of characters in a string are zero-based (i.e. the first character has an index of 0) so, if line has fewer than 11 characters (e.g. a length of 10), you will get the index out of bounds error if your substring ending index is >= 10 since the last character in a 10-character string would have an index of 9.
I won't put words into anyone's mouth, but I think that the way you expressed your search for a 'null' element might have led CEHJ to think that that 'null' was from a File, and if so, I can see why that happened. But he DID say it was an indexing error  - which it is - and in that sense I'd be grateful if you would award CEHJ the points rather than me this time. Up to you of course, but this is my comment. ; )

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial