user2567369
user2567369

Reputation:

java.lang.StringIndexOutOfBoundsException: while using charAt function

I want to get position of "," so i have used charAt function

below is the code

    public class JavaClass {

public static void main(String args[]){
    System.out.println("Test,Test".charAt(','));
}
}

but the problem is i am getting StringIndexOutOfBoundException can any body help me why i am getting this error

also i want to know that if ',' is not found than what the value will be return

error is below

      Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 44
at java.lang.String.charAt(Unknown Source)
at JavaClass.main(JavaClass.java:5)

Upvotes: 0

Views: 329

Answers (4)

Rahul
Rahul

Reputation: 45060

If you look at the method String#charAt(int index), you'll see that it takes in an int parameter. When you give ' character, it takes the ASCII value of that(which is 44) and tries to get the value at that index, which happens to be way more than the length of the String. And that is why you get the StringIndexOutOfBoundsException.

You need to use the indexOf() for this.

System.out.println("Test,Test".indexOf(','));

Upvotes: 1

Kanagaraj M
Kanagaraj M

Reputation: 966

charAt(int position) will take input parameter as integer. "," equivalent ascii value 44 because of this only your getting exception.

Upvotes: 1

zzxx53
zzxx53

Reputation: 423

You should use indexOf, rather than charAt System.out.println("Test,Test".indexOf(",")); charAt only returns the character at some position of the string; in this case it will be ascii code of ','

Upvotes: 3

rgettman
rgettman

Reputation: 178243

The charAt method expects an int representing the 0-based index where to look in the string. Unfortunately for you, the char you passed in, , can be converted to an int, 44, and there aren't 45 or more characters in your string, hence the StringIndexOutOfBoundsException.

Did you want to find the position of the , in your string? Then charAt is the wrong method. Try the indexOf method instead.

Upvotes: 5

Related Questions