String charAt() Method in Java with Example

Why use string "charAt" Method?

The charat method returns the character at the definite index. In this method index value should be between 0 and string length minus 1
Method Syntax:
public char charAt(int index)
Parameter input:
index – This Java method accepts only single input which is an int data type.
Method Returns:
This method returns a character type data based on the index input
Exception:
Throws java.lang.StringIndexOutOfBoundsException if index value is not between 0 and String length minus one
Example 1:
public class CharAtGuru99 {
    public static void main(String args[]) {
        String s1 = "This is String CharAt Method";
        //returns the char value at the 0 index
        System.out.println("Character at 0 position is: " + s1.charAt(0));
        //returns the char value at the 5th index
        System.out.println("Character at 5th position is: " + s1.charAt(5));
        //returns the char value at the 22nd index
        System.out.println("Character at 22nd position is: " + s1.charAt(22));
        //returns the char value at the 23th index
        char result = s1.charAt(-1);
        System.out.println("Character at 23th position is: " + result);
    }
}
Output:
Character at 0 position is: T
Character at 5th position is: i
Character at 22nd position is: M
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: -1
Some important things about this Java charAt method:
  • This Java method takes an argument which is always int type.
  • This method returns the character as char for the given int argument. The int value specifies the index that starts at 0.
  • If the index value is higher than string length or a negative, then IndexOutOfBounds Exception error occurs.
  • The index range must be between 0 to string_length-1.

No comments:

Post a Comment