Java String charAt method with Example

Java String charAt method with Example

The public char charAt(int index) will Returns the char value at the specified index. An index ranges from 0 to length() - 1. The first char value of the sequence is at index 0, the next at index 1, and so on, as for array indexing.if the index argument is negative or not less than the length of this string the we will get IndexOutOfBoundsException.

method signature

Example


public char charAt(int index)

package com.practice;

public class StringCharAtDemo {

public static void main(String[] args) {
String str = new String("java2study");

char c = str.charAt(3);
System.out.println(c);

char c1 = str.charAt(30);
System.out.println(c1);
}

}

output


a
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 30
at java.lang.String.charAt(String.java:658)
at com.practice.StringCharAtDemo.main(StringCharAtDemo.java:11)
-->