Java String charAt() Method with Examples

Get Job-ready: Java Course with 45+ Real-time Projects! - Learn Java

The charAt() method allows you to access individual characters in a String by specifying the index position. Indexing starts from 0, so the first character is at index 0, the second character is at index 1 and so on. The charAt() method in Java is used to return the character located at a specific index in a string.

The index passed to the charAt() method must be greater than or equal to 0 and less than the length of the string. If the index is out of bounds, it throws a StringIndexOutOfBoundsException.

Description of the Java charAt() method’s syntax

char charAt(int index)

Parameters and Return Type

It takes an int parameter representing the index and returns the char value at that index in the string.

Example Usage of Java String charAt() Method

Let’s look at some examples to better understand charAt() usage.

Example 1: Demonstrating the basic use of charAt()

public class Main {
  public static void main(String[] args) {
    String str = "Hello";
    char ch = str.charAt(0); 
    System.out.println(ch);
  }
}

Output:
H

Example 2: Illustrating the StringIndexOutOfBoundsException

public class Main {
  public static void main(String[] args) {
    String str = "Hello";
    char ch = str.charAt(10); // index out of bounds
    System.out.println(ch);
  }
}

Output:
Exception in thread “main” java.lang.StringIndexOutOfBoundsException: String index out of range: 10
at java.lang.String.charAt(String.java:658)
at Main.main(Main.java:5)

Programs Demonstrating charAt() Java Method

1) Accessing First and Last Character using charAt()

public class Main {
  public static void main(String[] args) {
    String str = "Hello World";
    
    // first character
    char first = str.charAt(0); 
    
    // last character
    int lastIndex = str.length() - 1;
    char last = str.charAt(lastIndex);
    
    System.out.println("First char: " + first);
    System.out.println("Last char: " + last);
  }
}

Output:
First char: H
Last char: d

2) Printing Characters at Odd and Even Positions

public class Main{  
  public static void main(String[] args){  
        
    String str = "JavaProgramming";
      
    System.out.print("Characters at odd position: ");
    for(int i=0; i<str.length(); i=i+2){
      System.out.print(str.charAt(i)); 
    }
    
    System.out.print("\nCharacters at even position: ");
    for(int i=1; i<str.length(); i=i+2){
       System.out.print(str.charAt(i));
    }
  }  
}

Output:
Characters at odd position: Jvrgamn
Characters at even position: aaPormig

3) Counting Frequency of a Character in a String

public class Main {
  public static void main(String[] args) {
     
    String str = "Picture perfect";
    char ch = 'p';
    
    int frequency = 0;
    
    for(int i=0; i<str.length(); i++) {
      if(ch == str.charAt(i)) {
        ++frequency;
      }
    }
    
    System.out.println("Frequency of " + ch + " = " + frequency);  
  }
}

Output:
Frequency of p = 3

Conclusion

The charAt() method in Java is an extremely useful string handling method that allows accessing and manipulating individual characters in a string. It takes an index as a parameter and returns the char value at that index position. One must be careful to pass a valid index between 0 and string length – 1; otherwise, it will result in StringIndexOutOfBoundsException.

This simple yet versatile method can be used along with loops and conditionals to accomplish various string manipulation tasks, such as finding first/last characters, accessing chars at odd/even positions, counting a char’s frequency, etc.

In summary, the charAt() method provides an indispensable way to efficiently handle character-level operations on Strings, making it a handy tool for Java programmers.

You give me 15 seconds I promise you best tutorials
Please share your happy experience on Google

courses

TechVidvan Team

TechVidvan Team provides high-quality content & courses on AI, ML, Data Science, Data Engineering, Data Analytics, programming, Python, DSA, Android, Flutter, full stack web dev, MERN, and many latest technology.

Leave a Reply

Your email address will not be published. Required fields are marked *