• Status: Solved
  • Priority: Low
  • Security: Public
  • Views: 139
  • Last Modified:

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

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.
0
softwarelovas
Asked:
softwarelovas
2 Solutions
 
CEHJCommented:
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

0
 
softwarelovasAuthor Commented:
Hmm.. I believe what I need to do is determine why I am receiving a out of bounds error.
0
 
krakatoaCommented:
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.
0
 
awking00Commented:
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.
0
 
krakatoaCommented:
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. ; )
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Cloud Class® Course: Microsoft Azure 2017

Azure has a changed a lot since it was originally introduce by adding new services and features. Do you know everything you need to about Azure? This course will teach you about the Azure App Service, monitoring and application insights, DevOps, and Team Services.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now