Java String CharAt(int index) Method

Java String CharAt(int index) Method

Well, the method name says ”char at”, so as the name says, this method is going to get us the character at the given index. We had some discussions earlier related to the indexing concept. We had discussed that the index of the strings starts from zero. For a string with length n, the final index is n – 1. So, knowing about these concepts, we can move further to understanding the implementation of the method. Remember that this method takes an index as an argument.

This is like asking hey… take this index and tell me what character is present in this index. As an example, let’s consider the string –

”GyaniPandit”, and if we try to invoke charAt(3), we are willing to get the character present at the index 3. Now, remembering that the index starts from zero, we have ‘G’ at 0, ‘y’ at 1, ‘a’ at 2, ‘n’ at 3, and so on. 10 is the last index, and the length of the string is found to be 11. So, for our method, we need the character at index 3, which is found to be ‘n’.

Let’s have an example program to understand the method in a better way –

public class StringMethods {
public static void main(String[] args) {
String exampleString = “GyaniPandit”;
System.out.println(exampleString.charAt(5));
}
}

If we try executing the above program, we have an output as ‘P’, which is the character present at index 5. Now the question is that what if we give such an index as an argument, which is greater than even the length of the given string? How is the method going to react to such an input?

Well, if we try doing this, the method will throw an exception, which is the StringIndexOutOfBoundsException. This just has to say that the index that you have given as an input is out of bounds for the string you are searching for.

So, in the above program, if we just change the 5 that we have given as an argument, to another value that is greater than or equal to the length of the string, like 50 (which is far bigger than the length of the string), then running the program again would throw an exception as stated above. You can give it a try though.