Search⌘ K

More on String Methods

Explore essential Java String methods such as charAt to access characters join to combine strings with delimiters replace to modify characters and case toggling for uppercase and lowercase conversion. This lesson helps you understand string handling techniques useful for the AP Computer Science exam and practical programming.

Finding a character at an index

Java provides the charAt() method, which when called on a string, returns the character at the specified index.

For example, if the string is “Java” and the index is 22, then ‘v’ will be returned. Below is a demonstration.

Let’s run a simple example.

Java
class CharacterAtIndex
{
public static void main(String args[])
{
String s1 = "Java";
System.out.println(s1.charAt(2)); // Character at index 2
System.out.println(s1.charAt(4)); // ❌ Error: Character at index 4
}
}

Look at line 6. We are obtaining the character of the string s1 at the 2nd index. It returns v as a result.

At line 7, we are obtaining the character of the string s1 at 4th index. It will give this error: IndexOutOfBoundsException. Attempting to access indices outside the range will result in an IndexOutOfBoundsException. In this case, the 4th index doesn’t exist. The maximum index value, ...