File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Java in General and the fly likes string index out of range Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "string index out of range" Watch "string index out of range" New topic

string index out of range

Ann Ron

Joined: Oct 21, 2003
Posts: 24
I am writing this code and getting an error : java.lang.StringIndexOutOfBoundsException: String index out of range: -70
This is my code snippet,Any idea how I solve this one..
String outstring = "123";
String repid;
String incno;
int MessageLength = MQ_Message.getMessageLength( );
outString = MQ_Message.readString(MessageLength);
repid = outString.substring(83,13);
incno = outString.substring(96,9);
Thanks in advance
Joe Ess

Joined: Oct 29, 2001
Posts: 8836

How about checking that variable MessageLength and seeing how long of a String you've received?

"blabbing like a narcissistic fool with a superiority complex" ~ N.A.
[How To Ask Questions On JavaRanch]
Ernest Friedman-Hill
author and iconoclast

Joined: Jul 08, 2003
Posts: 24183

You wrote

repid = outString.substring(83,13);
incno = outString.substring(96,9);

The two arguments to substring are the first (inclusive) and last (exclusive) character to include; it looks like you're assuming the second argument is a count, which it's not.
This and many other methods are documented in the online API Javadocs -- learn to use them, they'll save you a lot of trouble!
Now, beyond just the technical, and on to the stylistic: you've got a number "messageLength" which is the unknown length of a message. But your code is assuming that it will always be greater than 105. You might want to explicitly test that, and handle the error case where it's not. Just a thought -- otherwise, you'll soon be asking us about another mystery exception!

[Jess in Action][AskingGoodQuestions]
Matthew Brown

Joined: Apr 06, 2010
Posts: 4343

Raman Jha,
Your post was moved to a new topic.
I agree. Here's the link:
subject: string index out of range
Similar Threads
append to a text file at the end of the week
Cannot convert double to long..
Socket Programing using TCP Protocol
How to append to a text file for a week
cant find solution - OutOfBoundsException