Java OCAJP7: String indexOf method

There are four overloaded version of the indexOf method in the class String:

  • public int indexOf(int ch)
  • public int indexOf(int ch, int fromIndex)
  • public int indexOf(String str)
  • public int indexOf(String str, int fromIndex)

The two versions that define a second parameters use it as the index from which start searching. The following snippet shows an example when the index provided as search starting point is higher than the length of the string. In this case it takes the meaning of “search starting from the end of the string” without raising any exceptions like IndexOutOfBoundsException or stuff like that and the methods returns -1 because it cannot find any occurrences.
In fact, according to the official documentation “there is no restriction on the value of fromIndex. If it is negative, it has the same effect as if it were zero: this entire string may be searched. If it is greater than the length of this string, it has the same effect as if it were equal to the length of this string: -1 is returned.”

public class JavaCertification  {
	public static void main(String[] args) {  
		String s = "ABCDEF";

		// search for 'x' character starting from index 100
		int x = s.indexOf('K', 100);

		// No exceptions will be thrown and -1 will be returned
		System.out.println(x);
	}
}

This program produces the following output:

-1
This entry was posted in $1$s. Bookmark the permalink.

Leave a Reply

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