Java - String Character at an Index


Use the charAt() method to get a character at a particular index from a String object.

The index starts at zero. Index of a Character in a String Object.

Index ->          0      1       2      3      4
Character ->      H      E       L      L      O

The index of the first character H is 0 (zero), the second character E is 1, and so on.

The index of the last character O is 4, which is equal to the length of the string "Hello" minus 1.

The following snippet of code will print the index value and the character at each index in a string of "HELLO":


public class Main {
  public static void main(String[] args) {
    String str = "HELLO";

    // 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);
    }//from  w w w .jav a2 s .  co m