Java Data Type How to - Get each character from a String








Question

We would like to know how to get each character from a String.

Answer

You can use the charAt() method to get a character at a particular index from a String object. The index starts at zero.

The following code prints the index value and the character at each index in a string of "JAVA2S.COM":

public class Main {
  public static void main(String[] args) {
    String str = "JAVA2S.COM";
//  w ww .j a v  a  2 s . c  om
    // Get the length of string
    int len = str.length();

    // Loop through all characters and print their indexes
    for (int i = 0; i < len; i++) {
      System.out.println(str.charAt(i) + "  has  index   " + i);
    }

  }
}

The code above generates the following result.