How can you access a specific character in a string?

You can access a specific character in a string in Java using the charAt(int index) method. The index is zero-based, meaning the first character is at index 0.

Here's an example:

public class AccessCharacter {
    public static void main(String[] args) {
        String str = "Hello, World!";
        int index = 7; // Accessing the character at index 7
        char character = str.charAt(index);
        System.out.println("The character at index " + index + " is: " + character);
    }
}

In this example, the character at index 7 is 'W', and the output will be:

The character at index 7 is: W

0 Comments

no data
Be the first to share your comment!