Home >>Java String Methods >Java String charAt() method

Java String charAt() method

Java String charAt()

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.

Internal implementation


public char charAt(int index) 
{  
       if ((index < 0) || (index >= value.length)) 
	   {  
           throw new StringIndexOutOfBoundsException(index);  
       }  
       return value[index];  
   }  

Signature

public char charAt(int index) 

Parameter

Index - index of returnable character, starts with 0

Returns

char value - Returns character at position specified.

Java String charAt() method example

public class CharAtExample
{
public static void main(String args[])
{
String php="phptpoint";
char ChAt=php.charAt(2);
System.out.println(ChAt);
}
}

p

StringIndexOutOfBoundsException with charAt()

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);  
}}

Output
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 9
at java.lang.String.charAt(String.java:658)
at CharAtExample.main(CharAtExample.java:4)
Java String charAt() Example 3

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));      
    }  
}  

Output
Character at Zero index is: W
Character at last index is: d
Java String charAt() Example 4

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);  
    }  
}  

Output
Frequency of p is: 3

No Sidebar ads