Home >>Java String Methods >Java String charAt() method
The java string charAt() method returns a char value at the specified index number. The index value will have to be between 0 and length()-1.
If the given index number is greater than or equal to this string length or negative number, it returns StringIndexOutOfBoundsException.
public char charAt(int index)
{
if ((index < 0) || (index >= value.length))
{
throw new StringIndexOutOfBoundsException(index);
}
return value[index];
}
public char charAt(int index)
Index - index of returnable character, starts with 0
char value - Returns character at position specified.
public class CharAtExample
{
public static void main(String args[])
{
String php="phptpoint";
char ChAt=php.charAt(2);
System.out.println(ChAt);
}
}
Let's look at the example of the method charAt() where we transfer greater index value. In such case, at run time, it throws StringIndexOutOfBoundsException.
public class CharAtExample
{
public static void main(String args[])
{
String val="phptpoint";
char chT1=val.charAt(9);
System.out.println(chT1);
}}
Let's see a simple example from the given string where we reach first and last characters.
public class CharAtExample3
{
public static void main(String[] args) {
String strln = "Welcome to phptpoint world";
int strLength = strln.length();
System.out.println("Character at Zero index is: "+ strln.charAt(0));
System.out.println("Character at last index is: "+ strln.charAt(strLength-1));
}
}
Let's take an example where we count a character's frequency in the string.
public class CharAtExample4
{
public static void main(String[] args) {
String strl = "Welcome to phptpoint world";
int count = 0;
for (int i=0; i<=strl.length()-1; i++) {
if(strl.charAt(i) == 't') {
count++;
}
}
System.out.println("Frequency of p is: "+count);
}
}