This method takes one integer argument and return a character specified at index position. For any string the index value starts from 0 to string length -1 position. If passed index value not in valid range then it throws IndexOutOfBoundsException.
For example string Hello Friends contains 13 characters starting from 0 to 12 H is first position with index value 0, F is in seventh position with index value 6 and s is in 13 position with index value 12.
Using numbre other then 0 to 12( 0 to length()-1) will result in IndexOutOfBountException
Signature:
public char charAt(int index)
Parameters:
index -Integer index value to get character at specified index position.
Return:
Character at passed index value.
Exception Throws:
IndexOutOfBoundsException If index value in not between 0 to String length()-1
Example
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
public class StringChatAtExample { public static void main(String args[]) { String test = "Java String charAt() example"; char firstCharacter = test.charAt(0); char sixthCharacter = test.charAt(5); char lastCharacter = test.charAt(test.length() - 1); System.out.println("String:" + test); System.out.println("Character at first position: " + firstCharacter); System.out.println("Character at sixth position: " + sixthCharacter); System.out.println("Character at last position: " + lastCharacter); } } |
Result
1 2 3 4 |
String:Java String charAt() example Character at first position: J Character at sixth position: S Character at last position: e |
Now Print all characters with its index value
Example
1 2 3 4 5 6 7 8 9 |
public class StringChatAtExample1 { public static void main(String args[]) { String test = "Java String charAt() example"; for(int i=0;i<=test.length()-1;i++){ System.out.println("Character at index value "+i+" = "+test.charAt(i)); } } } |
Result
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
Character at index value 0 = J Character at index value 1 = a Character at index value 2 = v Character at index value 3 = a Character at index value 4 = Character at index value 5 = S Character at index value 6 = t Character at index value 7 = r Character at index value 8 = i Character at index value 9 = n Character at index value 10 = g Character at index value 11 = Character at index value 12 = c Character at index value 13 = h Character at index value 14 = a Character at index value 15 = r Character at index value 16 = A Character at index value 17 = t Character at index value 18 = ( Character at index value 19 = ) Character at index value 20 = Character at index value 21 = e Character at index value 22 = x Character at index value 23 = a Character at index value 24 = m Character at index value 25 = p Character at index value 26 = l Character at index value 27 = e |