String indexOf() method

Java String indexOf() method returns the position of the specified string or char from the given string. If the target string or character does not exist, it will return -1. The String indexOf() method is case-sensitive , so uppercase and lowercase chars are treated to be different. Syntax
int indexOf(int ch) returns index position for the given char value int indexOf(int ch, int fromIndex) returns index position for the given char value and from index int indexOf(String substring) returns index position for the given substring int indexOf(String substring, int fromIndex) returns index position for the given substring and from index
Example
class TestClass{ public static void main (String[] args){ String str = "Halo World!"; int idx1 = str.indexOf('d'); System.out.println("Index of 'd' is "+idx1); int idx3 = str.indexOf("World"); System.out.println("World is exist and position is "+idx3); int idx4 = str.indexOf("Halo",4); System.out.println("Position of Halo after index 4 is "+idx4); } }
Output
Index of 'd' is 9 World is exist and position is 5 Position of Halo after index 4 is -1

Java String lastIndexOf()

The lastIndexOf() method searches right-to-left inside the given string for a target string and returns the index of the last occurrence of the character in the character sequence. If the target string is not found, it will return -1. Syntax
int lastIndexOf(int ch)
Example
class TestClass { public static void main (String[] args){ String str = "Halo World!"; int idx1 = str.lastIndexOf('l'); System.out.println("last Index of 'l' is "+idx1); int idx2 = str.indexOf('l'); System.out.println("Index of 'l' is "+idx2); } }
Output
last Index of 'l' is 8 Index of 'l' is 2