Java String indexOf Method With Code Examples

By Sruthy

By Sruthy

Sruthy, with her 10+ years of experience, is a dynamic professional who seamlessly blends her creative soul with technical prowess. With a Technical Degree in Graphics Design and Communications and a Bachelor’s Degree in Electronics and Communication, she brings a unique combination of artistic flair…

Learn about our editorial policies.
Updated March 7, 2024

In this Tutorial, we will learn about the Java String indexOf() Method and its Syntax and Programming Examples to find the Index of Characters or Strings:

We will explore the other options that are associated with the Java indexOf() method and it’s usage along with simple programming examples.

Upon going through this tutorial, you will be able to understand the different forms of the String indexOf() Java method and you will be comfortable in using it in your own programs.

=> Check ALL Java Tutorials Here.

Java String - indexOf Method

Java String indexOf Method

As the name suggests, a Java String indexOf() method is used to return the place value or the index or the position of either a given character or a String.

The return type of the Java indexOf() is “Integer”.

Syntax

The syntax is given as int indexOf(String str) where str is a String variable and this will return the index of the first occurrence of the str.

Options

There are basically four different options/variations of using the Java indexOf() method.

  • int indexOf(String str)
  • int indexOf(String str, int StartingIndex)
  • int indexOf(int char)
  • int indexOf(int char, int StartingIndex)

As discussed earlier, the Java indexOf() method is used to return the place value of either a string or a character of the String. The indexOf() method comes up with two options each i.e. for String as well as the character.

We have already discussed the first variation and the second variation of Strings and characters that come up with the StartingIndex. This Starting Index is the index from where the search for the character index has to be started.

Finding The Index Of A Substring

This is the simplest form of the Java indexOf() method. In this example, we are taking an input String in which we are going to find the index of a substring that is a part of the main String.

public class indexOf {

	public static void main(String[] args) {
		String str = "Welcome to Softwaretestinghelp";
		
		//Printing the index of a substring "to"
		System.out.println(str.indexOf("to"));

	}

}

Output:

Finding The Index Of A Substring

Finding The Index Of A Character

In this example, we will see how the StartingIndex works when we try to find the index of the character from the main String. Here, we have taken an input String in which we are specifying the two different StartingIndex and see the difference too.

The first print statement returns 1 as it is searching from the 0th index whereas the second print statement returns 6 as it is searching from the 5th index.

public class indexOf {

	public static void main(String[] args) {
		String str = "Welcome";
		
		//returns 1 as it is searching from the 0th index
		System.out.println(str.indexOf("e", 0));
		
		//returns 6 as it is searching from the 5th index.
		System.out.println(str.indexOf("e", 5));

	}

}

Output:

Finding the index of a char

Scenarios

Scenario 1: What happens when we try to find the index of a character that is not available in the main String.

Explanation: Here, we have initialized a String variable and we are trying to get the index of the character as well as a substring which is not available in the main String.

In this type of scenario, the indexOf() method will always return -1.

public class indexOf {

	public static void main(String[] args) {
		String str = "Software Testing";
		
		/*
		 * When we try to find the index of a character or String
		 * which is not available in the Main String, then
		 * it will always return -1. 
		 */
		
		System.out.println(str.indexOf("X"));
		System.out.println(str.indexOf("x"));
		System.out.println(str.indexOf("y"));
		System.out.println(str.indexOf("z"));
		System.out.println(str.indexOf("abc"));

	}

}

Output:

Scenario where index always returns -1

Scenario 2: In this scenario, we will try to find the last occurrence of a character or substring in a given String.

Explanation: Here, we are going to be familiar with the additional method of the Java indexOf() method. The lastIndexOf() method is used to find the last occurrence of a character or substring.

In this example, we are fetching the last index of the character ‘a’. This can be accomplished by the Java indexOf() method as well as the lastIndexOf() method.

The lastIndexOf() method is easy to use in this kind of scenario as we do not require any StartingIndex to be passed. While using the indexOf() method, you can see that we have passed the StartingIndex as 8 from where the index will start and continue to find the occurrence of ‘a’.

public class indexOf {

	public static void main(String[] args) {
		String str = "Saket Saurav";
		
		/*
		 * The first print statement is giving you the index of first 
		 * occurrence of character 'a'. The second and third print 
		 * statement is giving you the last occurrence of 'a' 
		 */
		
		System.out.println(str.indexOf("a"));
		System.out.println(str.lastIndexOf("a"));
		System.out.println(str.indexOf("a", 8));

	}

}

Output:

find the last occurrence of a character or substring in a given String

Frequently Asked Questions

Q #1) How to find the length of a string in Java without using length method?

Answer: Java has an inbuilt method called length() that is used to find the length of a String. This is the standard way to find the length. However, we can also find the length of a String using the lastIndexOf() method but it cannot be used while we are providing input through the console.

Let’s see the below example where we have used both the methods to find the length of a String.

public class indexOf {

	public static void main(String[] args) {
		String str = "Software Testing Help";
		
		/* Here we have used both length() and lastIndexOf() method
		 * to find the length of the String.
		 */
		
		int length = str.length();
		int length2 = str.lastIndexOf("p");
		length2 = length2 + 1;
		
		// Printing the Length using length() method
		System.out.println("Length using length() method = " + length);
		
		// Printing the Length using lastIndexOf() method
		System.out.println("Length using lastIndexOf() method = " + length2);

	}

}

Output:

find the length of a string in java without using length method

Q #2) How to find the index of a dot in Java?

Answer: In the below program, we will find the index of ‘.’ that should be a part of the String. Here, we will take an input String that contains two ‘.’ and then with the help of indexOf() and lastIndexOf() methods, we will find the place value of the first and last dot ‘.’.

public class indexOf {

	public static void main(String[] args) {
		String str = "saket.saurav8@abc.com";
		
		/* Here, we are going to take an input String which contains two ‘.’ 
		 * and then with the help of indexOf() and lastIndexOf() methods, 
		 * we will find the place value of first and the last dot '.'
		 */
		
		System.out.println(str.indexOf('.'));
		System.out.println(str.lastIndexOf('.'));

	}

}

Output:

index of a dot in Java

Q #3) How to get the value of elements of an array in Java?

Answer:

Given below is the programming example to extract the elements of an array.

Elements start from arr[0], thus when we print arr[0]… till the last index, and we will be able to retrieve the elements specified at a given index. This can be done either by specifying the index number of the element or by using a loop.

public class indexOf {

	public static void main(String[] args) {
		String arr[] = {"Software", "Testing", "Help"};
		
		/* Elements start from arr[0], hence when we 
		 * print arr[0]... till the last index, we will
		 * be able to retrieve the elements specified at a 
		 * given index. This is also accomplished by using For Loop
		 */
		
		System.out.println(arr[0]);
		System.out.println(arr[1]);
		System.out.println(arr[2]);
		System.out.println();
		System.out.println("Using For Loop: ");
		
		for (int i=0; i< arr.length; i++) {
			System.out.println(arr[i]);
		}
	}

}

Output:

get the value of elements of an array in Java

Q #4) How to get the index of a list in Java?

Answer: In the below program, we have added some elements and then we have tried to find the index of any of the elements present in the list.

import java.util.LinkedList;
import java.util.List;

public class indexOf { 

    public static void main(String[] args) 
    { 
  
        /* Added a few elements in the list and then
         * found the index of any of the elements
         */
    	 
        List<Integer> list = new LinkedList<>(); 
        list.add(523); 
        list.add(485); 
        list.add(567); 
        list.add(999);
        list.add(1024); 
        System.out.println(list); 
        System.out.println(list.indexOf(999)); 
    } 
} 

Output:

Get the index of a list in Java

Q #5) How to get the second last index of the string in Java?

Answer: Here, we have found the second last index as well as the second last character occurring in the String.

As we have to find the second last character, we have subtracted 2 characters from the length of the String. Once the character is found, we have printed using chars[i] and the index of the second last character as well.

public class indexOf {

	public static void main(String[] args) {
		String str = "Software Testing Help";
		char[] chars = str.toCharArray();
		/* Since, we have to find the second last character, we have subtracted 2 characters
		 * from the length of the String. Once the character is found, we have printed
		 * using chars[i] and also the index of the second last character.
		 */
		
		for(int i=chars.length-2; i>0;) {
			System.out.println("The second last character is " + chars[i]);
			System.out.println("The index of the character is " + str.indexOf(chars[i]));
			break;
		}
		
		}
		
}

Output:

Get the second last index of the string in java

Conclusion

In this tutorial, we understood the Java String indexOf() method in detail along with the options that are associated with the Java indexOf() method.

For better understanding, this tutorial was explained with the help of different scenarios and FAQs along with adequate programming examples on each usage to explain the ways of using the indexOf() and lastIndexOf() methods.

=> Watch Out The Simple Java Training Series Here.

Was this helpful?

Thanks for your feedback!

Leave a Comment