Java String charAt() method

The charAt(int index) method in Java is used to retrieve the character at a specific index in a string. It is a part of the String class in Java.

To extract a single character from a String, you can refer directly to an individual character via the charAt( ) method. It has this general form:

Syntax:


public char charAt(int index)

Parameters:

index: The index of the character you want to access. The index is 0-based, meaning the first character is at index 0, the second at index 1, and so on.

Return Value: The method returns the character at the specified index in the string.

Example:


public class CharAtExample {
    public static void main(String[] args) {
        String str = "Hello, World!";
        
        // Retrieve the character at index 0 (first character)
        char charAt0 = str.charAt(0);
        System.out.println("Character at index 0: " + charAt0);  // Output: H
        
        // Retrieve the character at index 4 (5th character)
        char charAt7 = str.charAt(7);
        System.out.println("Character at index 7: " + charAt7);  // Output: o
    }
}

Handle StringIndexOutOfBoundsException

This exception is thrown if the index is negative or greater than or equal to the length of the string.

Example:


public class CharAtExceptionExample {
    public static void main(String[] args) {
        String str = "Hello, World!";
        try {
            char invalidChar = str.charAt(18);
        } catch (StringIndexOutOfBoundsException e) {
            System.out.println("Error: " + e.getMessage());  // Output: String index out of range: 18
        }
       
}

Note: If you attempt to access an index that is out of the bounds of the string (such as str.charAt(18)), it will throw a StringIndexOutOfBoundsException.

Java String charAt() method – Interview Questions

Q 1: What does charAt() method do?
Ans: Returns the character at a specific index.
Q 2: What is the index range for charAt()?
Ans: 0 to length()-1.
Q 3: What exception is thrown if index is invalid?
Ans: StringIndexOutOfBoundsException.
Q 4: What is the return type of charAt()?
Ans: char.
Q 5: Is charAt() case-sensitive?
Ans: Yes, it returns exact character.

Java String charAt() method – Objective Questions (MCQs)

Q1. The charAt() method in Java returns:






Q2. What will be the output of the following code?

String s = "Java";
System.out.println(s.charAt(2));






Q3. What happens if the index passed to charAt() is greater than or equal to the string length?






Q4. What is the return type of charAt() method?






Q5. What will be the output of the following code?

String str = "World";
char ch = str.charAt(0);
System.out.println(ch);






Related Java String charAt() method Topics