String problem

I have a String named in. When I call in.charAt(0) I get StringIndexOutOfBoundsException. Why is this happening when the String is neither null nor ""?
Who is Participating?
cphConnect With a Mentor Commented:
How did you define in? Is it like: String in;
or did you define an array of String?
In the first case if you init you string in to "abc", then in.chatAt(0); is perfectly valid.
However in the second case, you have to specify which index you want, eg in[0].charAt(0);

Also you should know that if you define a length to a string via some of the constructors then the max index if the length-1.

incahAuthor Commented:
<in> is a String (not array of Strings) parameter in a method, and when this method is called, <in> is coming from a database via ResultSet.getString() . Any other ideas?
Did you call the next method before assigning the String?
Let's say you have a variable called result as ResultSet,

you have to do first, then you can assign in to result.getString() if there's any row returned
7 new features that'll make your work life better

It’s our mission to create a product that solves the huge challenges you face at work every day. In case you missed it, here are 7 delightful things we've added recently to monday to make it even more awesome.

So you have something like, in=ResultSet.getString();
ResultSet is not null, 'cos you'd get an Null pointer exception... (but it's still worth a check)
Have you try to get the length() of the string, ie in.length(); and see what's the value.

incahAuthor Commented:
The string is not null and has a length because as my method is written it wouldn't reach to the point where in.charAt() is called. Anyway I printed the length to the standard output and it is 4.
incahAuthor Commented:
Please forget the question. The exception was happening when StringBuffer.setCharAt() was called, and not on String.atChar(). My mistake. Sorry.
Well at least you found it :)
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.

All Courses

From novice to tech pro — start learning today.