Java String charAt()

As you know String is array of characters and each character stores at different index value. Sometimes, there are situations we want to get the character from a string. The Java String charAt() method is used to get the character.

This method is used to get the character at the specified index. it is used when we want to get first character of string java. The index number should be between the 0 to length-1. If length is not lies between 0 to length-1 it will throw StringIndexOutOfBoundsException.

Java String charAt()

The return type of charAt() is char. Where char is a data type used for characters.

stringName.chartAt(index)

stringName: The name of string in which you want to find the character.
index: Index will be the position of the character in a string. It should be an integer from 0 to length-1.

class ExampleOfCharAt
{  
   public static void main(String args[])
   {  
	 String name = "JavaGoal";  
	 Char charAtPosition = name.charAt(3); //returns the char value at the 3th index  
	 System.out.println("The character present at index 3 is = " +charAtPosition);  
   }
} 

Output: The character present at index 3 is = a

StringIndexOutOfBoundsException with charAt()

The index should be an integer and it should be lies between the 0 to length-1. If you will try to with any illegal index value it will throw an exception.

class PerformanceExample
 {  
    public static void main(String args[])
    {  
	 String name = "Java";  
	 char charAtPosition = name.charAt(5); //returns the char value at the 5th index  
	 System.out.println("The character present at index 5 is = " +charAtPosition);  
    }
}  

Output: Exception in thread “main” java.lang.StringIndexOutOfBoundsException: String index out of range: 5 at java.base/java.lang.StringLatin1.charAt(StringLatin1.java:47) at java.base/java.lang.String.charAt(String.java:693) at PerformanceExample.main(PerformanceExample.java:6)

Leave a Comment