0

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)
1
  • 2
    Read the charAt javadoc and read about primitive types. ',' is considered an int in that method call. String index out of range: 44 should've given that away. Commented Oct 16, 2013 at 17:27

4 Answers 4

5

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.

Sign up to request clarification or add additional context in comments.

Comments

3

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 ','

Comments

1

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

Comments

1

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(','));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.