Ticker

6/recent/ticker-posts

String charAt() Method in Java — Learn with Example

String charAt() Method in Java — Learn with Example

Introduction:
The charAt() method is a built-in function in Java that is used to retrieve the character at a specified index from a String. In Java, strings are represented as an array of characters, and the charAt() method provides a simple way to access individual characters within the string.

Syntax:

java
public char charAt(int index)

Parameters:

  • index: An integer value representing the index of the character to be retrieved. It should be within the range of 0 to length() - 1 of the string.

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

Example:

java
public class CharAtExample {
public static void main(String[] args) {
String str = "Hello, World!";

// Get the character at index 4
char result = str.charAt(4);

// Print the result
System.out.println("Character at index 4: " + result);
}
}

Explanation:
In the given example, we have a string str initialized with the value "Hello, World!". We then use the charAt() method to retrieve the character at index 4, which corresponds to the comma character (,). The charAt() method returns this character, and we store it in the result variable.

Finally, we print the result using System.out.println(), and the output will be:


Character at index 4: ,

Please note that the indexing of characters in a string starts from 0, so the first character is at index 0, the second at index 1, and so on. Attempting to access an index outside the valid range (less than 0 or greater than or equal to the length of the string) will result in a StringIndexOutOfBoundsException.

Post a Comment

0 Comments