Difference between charAt() and indexOf() in Java ?

Java 8Object Oriented ProgrammingProgramming

The charAt() method of the String class returns the char value at the specified index. An index ranges from 0 to length() - 1. The first char value of the sequence is at index 0, the next at index 1, and so on, as for array indexing.

The indexOf(int ch, int fromIndex) method of the String class returns the index within this string of the first occurrence of the specified character, starting the search at the specified index.
If a character with value ch occurs in the character sequence represented by this String object at an index no smaller than fromIndex, then the index of the first such occurrence is returned.

Example

 Live Demo

public class CharAt_IndexOf_Example {
   public static void main(String args[]){
      String str = "This is tutorialspoint";
      System.out.println("Index of letter 't' = "+ str.indexOf('t', 14));
      System.out.println("Letter at the index 8 is ::"+str.charAt(8));
   }
}

Output

Index of letter 't' = 21
Letter at the index 8 is ::t
raja
Published on 12-Feb-2018 14:34:37
Advertisements