Using CharAt in Java

Java, a versatile and widely used programming language, boasts many built-in functions that simplify string manipulation. Among these is the charAt() function, housed within the String class. This function's primary role is to retrieve a character at a specific index position within a given string. Given that Java adopts a zero-based indexing system, the initial feeling of a string is found at index 0, the subsequent one at index 1, and the pattern continues. Such a method ensures that programmers can swiftly pinpoint and extract desired characters from lengthy strings, paramount in scenarios demanding precise text parsing or modification. However, one must tread with caution. Supplying an index that surpasses the string's boundaries or is negative is perilous, as it will instantly trigger a StringIndexOutOfBoundsException. This exception arises when one attempts to access a position that doesn't exist within the string's confines. Hence, it's imperative to always validate the index against the string's length before invoking the charAt() function. In this Java CharAt Example, we showed an example of using the charAt method. Click Execute to run the Java CharAt Example online and see the result.
Using CharAt in Java Execute
public class CharAtExample {

    public static void main(String[] args) {
        String sample = "Hello, World!";

        char fifthChar = sample.charAt(4);
        System.out.println("Fifth character of the string: " + fifthChar);

        for (int i = 0; i < sample.length(); i++) {
            char currentChar = sample.charAt(i);
            System.out.println("Character at index " + i + ": " + currentChar);
Updated: Viewed: 36 times