String

String indexOf Java Example

In this post, we feature a comprehensive String indexOf Java Example. We also describe an example of the lastIndexOf in Java .

It is often important to search for a character or a character set in a Java String. For example, in the parsing of Java Strings, we might want to provide the possibility for a search through strings, in order to find a specific character or word. Thus we need a “tool”, a method that will help us make it.

So, in this example, we are going to talk about identifying characters and subsequences of characters through Java Strings, with the methods indexOf() and lastIndexOf().

1. String indexOf Java methods

1.1 Prerequisites

Java 8 is required on the Linux, windows or mac operating system. Eclipse Oxygen can be used for this example.

1.2 Download

You can download Java 8 from the Oracle web site . Eclipse Oxygen can be downloaded from the eclipse web site.

1.3 Setup

Below are the setup commands required for the Java Environment.

Setup

JAVA_HOME="/desktop/jdk1.8.0_73"
export JAVA_HOME
PATH=$JAVA_HOME/bin:$PATH
export PATH

1.4 IDE

1.4.1 Eclipse Oxygen Setup

The ‘eclipse-java-oxygen-2-macosx-cocoa-x86_64.tar’ can be downloaded from the eclipse website. The tar file is opened by double click. The tar file is unzipped by using the archive utility. After unzipping, you will find the eclipse icon in the folder. You can move the eclipse icon from the folder to applications by dragging the icon.

1.5 Launching IDE

1.5.1 Eclipse Java

Eclipse has features related to language support, customization, and extension. You can click on the eclipse icon to launch eclipse. The eclipse screen pops up as shown in the screenshot below:

indexOf Java - Eclipse Launch
Eclipse Launch

You can select the workspace from the screen which pops up. The attached image shows how it can be selected.

indexOf Java - Eclipse Workspace
Eclipse Workspace

You can see the eclipse workbench on the screen. The attached screenshot shows the Eclipse project screen.

indexOf Java - Eclipse Workbench
Eclipse Workbench

Java Hello World class prints the greetings. The screenshot below is added to show the class and execution on eclipse.

indexOf Java - Java Hello
Java Hello

1.6 String static indexOf() method

The indexOf()(String or character target) method searches left-to-right inside the given string for a “target” string. The method returns the index number where the target string is first found or -1 if the target is not found. Like equals(), the indexOf() method is case-sensitive, so uppercase and lowercase chars are considered to be different.

  • int indexOf(String str): Returns the index within this string of the first occurrence of the specified substring. If it does not occur as a substring, -1 is returned.
  • int indexOf(String str, int fromIndex): Returns the index within this string of the first occurrence of the specified substring, starting at the specified index. If it does not occur, -1 is returned.

We can use the same methods in order to find the index of the first occurrence of a specified character within the string:

  • int indexOf(int ch)
  • int indexOf(int ch, int fromIndex)

Let’s see the following code example:

JavaStringIndexOf.java

 
public class JavaStringIndexOf {
 
   public static void main(String args[]) {
 
   String str = new String("Hello JavaCodeGeeks! This is my very first post.");
 
   String subStr1 = new String("JavaCodeGeeks");
   String subStr2 = new String("JavaGeeks");
 
   System.out.print("Found Index :");
   System.out.println(str.indexOf('e')); //finds the first occurence of 'e'
 
   System.out.print("Found Index :");
   System.out.println(str.indexOf('e', 5)); //finds the occurence of 'e' after the 5th character
 
   System.out.print("Found Index :");
   System.out.println(str.indexOf(subStr1)); //finds the first occurence of "JavaCodeGeeks"
 
   System.out.print("Found Index :");
   System.out.println(str.indexOf(subStr1, 15)); //finds the occurence of "JavaCodeGeeks" after the 15th character
 
   System.out.print("Found Index :");
   System.out.println(str.indexOf(subStr2)); //finds the first occurence of "JavaGeeks"
 
   }
}

Output

Found Index :1
Found Index :13
Found Index :6
Found Index :-1
Found Index :-1

1.7 String lastIndexOf() method

The lastIndexOf method has four different variations. The variations are listed below:

  • int lastIndexOf(int cha)
  • lastIndexOf(int cha, int start)
  • lastIndexOf(String string)
  • int lastIndexOf(String string, int start)

The first method with int as the parameter finds the index of the last occurrence of the input character in the string. The second method with two parameters int character and int start index finds the index of the last occurrence of the input character in the string before the point of the start index.

The third method with String as a parameter finds the occurrence of the substring within the string. The fourth method with String and int start index finds the index in the string for the last occurrence of the substring starting at the input index.

The code sample is attached below to demonstrate the four variants of the lastIndexOf method.

Let’s see the following example:

StringLastIndexExample

/**
 * @author bhagvan.kommadi
 *
 */
public class StringLastIndexExample {
     
    public static void main(String args[]) 
    { 
    
        String strExample = new String("string example of"); 
         
        System.out.println("The length of the string is " +strExample.length());
   
        System.out.print("The Last Index of p at : "); 
   
         
        System.out.println(strExample.lastIndexOf('p')); 
         
        System.out.print("The Last Index of p before 16 at : "); 
     
        System.out.println(strExample.lastIndexOf('p', 16)); 
         
        System.out.print("The Last Index of exam at : "); 
         
        System.out.println(strExample.lastIndexOf("exam"));
       
        System.out.print("The Last Index of exam before 16 at : "); 
     
        System.out.println(strExample.lastIndexOf("exam", 16));
    } 
 
}

The output of the above code example when executed is shown in the screenshot below.

LastIndexOf Method

2.  Download the Source Code

That was a String indexOf Java Example.

Download
You can download the full source code of this example here: String indexOf Java Example

Last updated on Feb. 25th, 2020

Chryssa Aliferi

Chryssa is a Computer Science graduate from Athens University of Economic and Business. During her studies, Chryssa carried out a great variety of projects ranging from networking to software engineering. She is very keen on front end development especially on mobile technologies and web applications. She has worked as a junior Software Engineer in the telecommunications area and currently works as an Android Developer.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button