Site icon TechVidvan

Java String charAt() Method

java string charat ()

We are going to discuss the String charAt() function in Java.

The Java String returns the character in a string at the given position charAt(int index) function. The index value should fall between 0 and (length of string-1).

Explanation

Syntax:

public char charAt(int index)

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

Parameter

Index – An int integer that represents the character’s index to return

Return Value

Returns: The char value for this string at the given index.
Index 0 contains the first character value.

Signature

Specified by

CharSequence interface, located inside java.lang package.

Exceptions

Diagram

Example 1:

public class CharAt{  
public static void main(String args[]){  
String name="Greatest";  
char ch=name.charAt(3);
System.out.println("The Character is:",ch);  
}
}

Output:
The Character is a.

Example 2:

public class CharAtExample{  
public static void main(String args[]){  
String name="Tremendous";  
char ch=name.charAt(10);
System.out.println(ch);  
}
}

Output:
String index out of range: 10
StringIndexOutOfBoundsException has occurred.

Example 3:

public class CharAtExample3 {  
    public static void main(String[] args) {  
    String str = "Great think takes time";      
    int strLength = str.length();      
    System.out.println("First Character is: "+ str.charAt(0));      
    System.out.println("Last Character is: "+ str.charAt(strLength-1));      
    }  
}

Output :
First Character is: G
Last Character is: e

Example 4:

public class CharAt{  
    public static void main(String[] args) {  
        String str = "Blue is our favourite colour";  
        int count = 0;  
        for (int i=0; i<=str.length()-1; i++) {  
            if(str.charAt(i) == 'o') {  
                count++;  
            }  
        }  
        System.out.println("Frequency of o is: "+count);  
    }  
}

Output:
Frequency of o is: 3

Difference between charAt() and indexOf()

Used to find

Importance of String charAt()

Advantages of String charAt()

Disadvantages of String charAt()

Conclusion

We extensively learn the Java string CharAt() function method. It is used in various methods of function in characters.

When a character value is searched for in a string, Java’s built-in charAt() function delivers the character value at the specified index number.

Exit mobile version