How do you get the index of the first occurance of character O in string Hello?

The Java String class indexOf() method returns the position of the first occurrence of the specified character or string in a specified string.

Signature

There are four overloaded indexOf() method in Java. The signature of indexOf() methods are given below:

No.MethodDescription1int indexOf(int ch)It returns the index position for the given char value2int indexOf(int ch, int fromIndex)It returns the index position for the given char value and from index3int indexOf(String substring)It returns the index position for the given substring4int indexOf(String substring, int fromIndex)It returns the index position for the given substring and from index

Parameters

ch: It is a character value, e.g. 'a'

fromIndex: The index position from where the index of the char value or substring is returned.

substring: A substring to be searched in this string.

Returns

Index of the searched string or character.

Internal Implementation

Java String indexOf() Method Example

FileName: IndexOfExample.java

Test it Now

Output:

We observe that when a searched string or character is found, the method returns a non-negative value. If the string or character is not found, -1 is returned. We can use this property to find the total count of a character present in the given string. Observe the following example.

FileName: IndexOfExample5.java

Output:

In the String: Welcome to JavaTpoint
The 'o' character has come 3 times

Java String indexOf(String substring) Method Example

The method takes substring as an argument and returns the index of the first character of the substring.

FileName: IndexOfExample2.java

Test it Now

Output:

Java String indexOf(String substring, int fromIndex) Method Example

The method takes substring and index as arguments and returns the index of the first character that occurs after the given fromIndex.

FileName: IndexOfExample3.java

Test it Now

Output:

index of substring 16
index of substring -1

Java String indexOf(int char, int fromIndex) Method Example

The method takes char and index as arguments and returns the index of the first character that occurs after the given fromIndex.

The index() method returns the index of a substring inside the string (if found). If the substring is not found, it raises an exception.

Example

text = 'Python is fun'

# find the index of is result = text.index('is')

print(result) # Output: 7


index() Syntax

It's syntax is:

str.index(sub[, start[, end]] )

index() Parameters

The index() method takes three parameters:

  • sub - substring to be searched in the string str.
  • start and end(optional) - substring is searched within str[start:end]

index() Return Value

  • If substring exists inside the string, it returns the lowest index in the string where substring is found.
  • If substring doesn't exist inside the string, it raises a ValueError exception.

The index() method is similar to the find() method for strings.

The only difference is that find() method returns -1 if the substring is not found, whereas index() throws an exception.

A string is a collection of characters nested in double quotes. The indexOf method returns the index position of a specified character or substring in a string.

In this article, we'll see the syntax for the different indexOf methods. We'll also look at some examples to help you understand and use them effectively to find the index of a character or substring in your Java code.

Syntax for the indexOf Method

The indexOf method has the following methods:

public int indexOf(int char)
public int indexOf(int char, int fromIndex)
public int indexOf(String str)
public int indexOf(String str, int fromIndex)

Let's explain these parameters before seeing some examples:

  • public class Main {
      public static void main(String[] args) {
        String greetings = "Hello World";
        
        System.out.println(greetings.indexOf("o"));
        
        // 4
      }
    }
    
    0 represents a single character in a string.
  • public class Main {
      public static void main(String[] args) {
        String greetings = "Hello World";
        
        System.out.println(greetings.indexOf("o"));
        
        // 4
      }
    }
    
    1 signifies the position where the search for the index of a character or substring should begin. This is important where you have two characters/strings that have the same value in a string. With this parameter, you can tell the indexOf method where to start its operation from.
  • public class Main {
      public static void main(String[] args) {
        String greetings = "Hello World";
        
        System.out.println(greetings.indexOf("o"));
        
        // 4
      }
    }
    
    3 represents a substring in a string.

Don't worry if you don't yet understand how any of this works – the examples will make it all clear!

How to Use the indexOf Method in Java

In the first example below, we'll find the index of a single character in a string. This example will help us understand the

public class Main {
  public static void main(String[] args) {
    String greetings = "Hello World";
    
    System.out.println(greetings.indexOf("o"));
    
    // 4
  }
}
4 method.

public class Main { public static void main(String[] args) { String greetings = "Hello World"; System.out.println(greetings.indexOf("o")); // 4 } } 5 Method Example

public class Main {
  public static void main(String[] args) {
    String greetings = "Hello World";
    
    System.out.println(greetings.indexOf("o"));
    
    // 4
  }
}

In the code above, we got the index of the character "0" returned to us which is 4. We have two "o" characters but the index of the first one got returned.

In the next example, we'll see how we can return the index of the second "o" in the next example.

If you're wondering how the index numbers are derived then you should note that the first character in a string has an index of zero, the second character has an index of one, and so on.

public class Main { public static void main(String[] args) { String greetings = "Hello World"; System.out.println(greetings.indexOf("o")); // 4 } } 6 Method Example

Here's an example that explains the

public class Main {
  public static void main(String[] args) {
    String greetings = "Hello World";
    
    System.out.println(greetings.indexOf("o"));
    
    // 4
  }
}
7 method:

public class Main {
  public static void main(String[] args) {
    String greetings = "Hello World";
    
    System.out.println(greetings.indexOf("o", 5));
    
    // 7
  }
}

In the example above, we are telling the indexOf method to begin its operation from the fifth index.

H => index 0

e => index 1

l => index 2

l => index 3

0 => index 4

Note that index 5 is not the character "W". The fifth index is the space between "Hello" and "World".

So from the code above, every other character that comes before the fifth index will be ignored. 7 is returned as the index of the second "o" character.

public class Main { public static void main(String[] args) { String greetings = "Hello World"; System.out.println(greetings.indexOf("o")); // 4 } } 9 Method Example

In the next example, we'll understand how the

public class Main {
  public static void main(String[] args) {
    String greetings = "Hello World";
    
    System.out.println(greetings.indexOf("o", 5));
    
    // 7
  }
}
0 method which returns the index of a substring works.

public class Main {
  public static void main(String[] args) {
    String motivation = "Coding can be difficult but don't give up";
    
    System.out.println(motivation.indexOf("be"));
    
    // 11
  }
}

Wondering how we got 11 returned? You should check the last section to understand how indexes are counted and how spaces between substrings count as indexes as well.

Note that when a substring is passed in as a parameter, the index returned is the index of the first character in the substring – 11 is the index of the "b" character.

public class Main { public static void main(String[] args) { String greetings = "Hello World"; System.out.println(greetings.indexOf("o", 5)); // 7 } } 1 Method Example

The last method –

public class Main {
  public static void main(String[] args) {
    String greetings = "Hello World";
    
    System.out.println(greetings.indexOf("o", 5));
    
    // 7
  }
}
2 – is the same as the
public class Main {
  public static void main(String[] args) {
    String greetings = "Hello World";
    
    System.out.println(greetings.indexOf("o", 5));
    
    // 7
  }
}
3 method. It returns an index from a specified position.

Here is an example:

public class Main {
  public static void main(String[] args) {
    String motivation = "The for loop is used for the following";
    
    System.out.println(motivation.indexOf("for", 5));
    
    // 21
  }
}

In the example above, we have specified that the method should start its operation from the fifth index which is the index that comes after the first "for" substring. 21 is the index of the second "for" substring.

Lastly, when we pass in a character or substring that doesn't exist in a string, the indexOf method will return a value of -1. Here is an example:

public class Main {
  public static void main(String[] args) {
    String motivation = "The for loop is used for the following";
    
    System.out.println(motivation.indexOf("code"));
    
    // -1
  }
}

Conclusion

In this article, we learned how to use the four indexOf methods with an example explaining each of the different methods.

We also saw what the syntax for each of these methods looks like and how they are able to tell the index to return.

We ended by showing what happens when a character or substring that doesn't exist is passed in as a parameter.

Happy coding!

ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT


How do you get the index of the first occurance of character O in string Hello?
Ihechikara Vincent Abba

This author's bio can be found in his articles!


If you read this far, tweet to the author to show them you care. Tweet a thanks

Learn to code for free. freeCodeCamp's open source curriculum has helped more than 40,000 people get jobs as developers. Get started