I am afraid, you are not close.

Here's what you have to do:

  • Loop on the characters of the string (the one on which you are supposed to do an indexOf, I will call this the master) (you are going this right)
  • For every character check whether your other string's character and this character are the same.
  • If they are (a potential start of the same sequence) check whether the next characters in the master match with your String to check (You might want to loop through the elements of the string and check one by one).
  • If they don't match, continue with the characters in the master string

Something like:

Loop master string
for every character (using index i, lets say)
   check whether this is same as first character of the other string
   if it is
      //potential match
      loop through the characters in the child string (lets say using index j)

      match them with the consecutive characters in the master string 
      (something like master[j+i] == sub[j])

       If everything match, 'i' is what you want
       otherwise, continue with the master, hoping you find a match

Some other points:

  • In java, method names start with a lower case letter by convention (meaning, the compiler won't complain, but your fellow programmers may). So IndexOf should actually be indexOf
  • Having instance variables (class level variables) start with a _ (as in _st) is not a really good practice. If your professor insists, you may not have many options, but keep this in mind)
Answer from Nivas on Stack Overflow
🌐
Oracle
docs.oracle.com › javase › 8 › docs › api › java › lang › String.html
String (Java Platform SE 8 )
April 21, 2026 - Object.equals(java.lang.Object), System.identityHashCode(java.lang.Object) public int indexOf(int ch) Returns the index within this string of the first occurrence of the specified character. If a character with value ch occurs in the character sequence represented by this String object, then ...
🌐
W3Schools
w3schools.com › java › ref_string_indexof.asp
Java String indexOf() Method
Java Examples Java Videos Java Compiler Java Exercises Java Quiz Java Code Challenges Java Practice Problems Java Server Java Syllabus Java Study Plan Java Interview Q&A · ❮ String Methods · Search a string for the first occurrence of "planet": String myStr = "Hello planet earth, you are a great planet."; System.out.println(myStr.indexOf("planet")); Try it Yourself » ·
Discussions

java - indexOf (String str) - equals string to other string - Stack Overflow
I need to write method that will chek "String str" on other string, and return the index that the str starts. That's sound like homework, and it is some of homework but for my use to learn for a t... More on stackoverflow.com
🌐 stackoverflow.com
indexOf - anyone got a simple explanation?
indexOf returns the index of where whatever you're searching for *starts*. String indices are zero-based Look at this https://docs.oracle.com/javase/7/docs/api/java/lang/String.html#indexOf(java.lang.String,%20int) After you find the first one you'll have to "move over" the length of whatever you're searching for and start searching there or it'll find the first one again. More on reddit.com
🌐 r/learnjava
8
10
April 2, 2019
Java String.indexOf and empty Strings - Stack Overflow
I'm curious why the String.indexOf is returning a 0 (instead of -1) when asking for the index of an empty string within a string. The Javadocs only say this method returns the index in this string... More on stackoverflow.com
🌐 stackoverflow.com
algorithm - java indexof(String str) method complexity - Stack Overflow
Possible Duplicate: What is the cost / complexity of a String.indexof() function call What is the complexity of java indexof(String str) method. I mean there are String matching algorithms lik... More on stackoverflow.com
🌐 stackoverflow.com
🌐
GeeksforGeeks
geeksforgeeks.org › java › java-string-indexof
Java String indexOf() Method - GeeksforGeeks
November 19, 2024 - In Java, the String indexOf() method returns the position of the first occurrence of the specified character or string in a specified string.
🌐
CodingBat
codingbat.com › doc › java-string-indexof-parsing.html
Java String indexOf Parsing
int indexOf(String target, int fromIndex) -- searches left-to-right for the target as usual, but starts the search at the given fromIndex. The fromIndex does not actually need to be valid. If it is negative, the search happens from the start of the string.
🌐
CodeGym
codegym.cc › java blog › strings in java › java string indexof()
Java String indexOf()
December 26, 2024 - We used a while loop to iterate over all occurrences of the character or substring until the indexOf() method returns -1, which indicates that there are no more occurrences of the character or substring in the string. The method java string indexOf has four different variations:
🌐
Codecademy
codecademy.com › docs › java › strings › .indexof()
Java | Strings | .indexOf() | Codecademy
May 13, 2022 - Returns the zero-indexed position of the first occurrence of the given character(s) in a string.
Find elsewhere
🌐
freeCodeCamp
freecodecamp.org › news › indexof-in-java-how-to-find-the-index-of-a-string-in-java
indexOf in Java – How to Find the Index of a String in Java
March 24, 2022 - In the next example, we'll understand how the public int indexOf(String str) method which returns the index of a substring works.
Top answer
1 of 5
3

I am afraid, you are not close.

Here's what you have to do:

  • Loop on the characters of the string (the one on which you are supposed to do an indexOf, I will call this the master) (you are going this right)
  • For every character check whether your other string's character and this character are the same.
  • If they are (a potential start of the same sequence) check whether the next characters in the master match with your String to check (You might want to loop through the elements of the string and check one by one).
  • If they don't match, continue with the characters in the master string

Something like:

Loop master string
for every character (using index i, lets say)
   check whether this is same as first character of the other string
   if it is
      //potential match
      loop through the characters in the child string (lets say using index j)

      match them with the consecutive characters in the master string 
      (something like master[j+i] == sub[j])

       If everything match, 'i' is what you want
       otherwise, continue with the master, hoping you find a match

Some other points:

  • In java, method names start with a lower case letter by convention (meaning, the compiler won't complain, but your fellow programmers may). So IndexOf should actually be indexOf
  • Having instance variables (class level variables) start with a _ (as in _st) is not a really good practice. If your professor insists, you may not have many options, but keep this in mind)
2 of 5
2

Not really very close, I'm afraid. What that code basically does is check there if the two strings have two characters in the same positions at any point and, if so, returns the index of the second of those characters. E.g., if _str is "abcdefg" and str is "12cd45", you'll return 3 because they have "cd" in the same place, and that's the index of the "d". At least, that's as near as I can tell what it's actually doing. That's because you're indexing into both strings with the same indexing variable.

To re-write indexOf, looking for str within _st, you have to scan _st for the first character in str and then check whether the remaining characters match; if not, bump forward one place from where you started checking and continue your scan. (There are optimisations you can do, but that's the essence of it.) So for instance, if you find the first character of str at index 4 in _st and str is six characters long, having found the first character you need to see if the remaining five (str's indexes 1-5 inclusive) match _st's indexes 5-10 inclusive (easiest just to check all six of str's characters against a substring of _st starting at 4 and going for six charactesr). If everything matches, return the index at which you found the first character (so, 4 in that example). You can stop scanning at _st.length() - str.length() since if you haven't found it starting prior to that point, you're not going to find it at all.

Side point: Don't call the length function on every loop. The JIT may be able to optimize out the call, but if you know that _st won't change during the course of this function (and if you don't know that, you should require it), grab length() to a local and then refer to that. And of course, since you know you can stop earlier than length(), you'l use a local to remember where you can stop.

🌐
Medium
medium.com › @AlexanderObregon › javas-arraylist-indexof-method-explained-6bb47ce4c894
Java’s ArrayList.indexOf() Method Explained | Medium
August 19, 2024 - In this example, the indexOf() method is used to locate the first occurrence of the operation 'C' in the list. The method returns 2, indicating the position of 'C' in the ArrayList. Since 'Z' is not present, the method returns -1. Imagine you’re managing a list of configuration parameters stored as strings, and you need to determine the position of a particular parameter in the list. import java...
🌐
FavTutor
favtutor.com › blogs › java-indexof
indexOf Method in Java (with Examples)
November 18, 2023 - The indexOf() method is a member of the String class in Java and is used to find the position of the first occurrence of a specified character or substring within a given string. It returns the index as an integer value, which represents the ...
🌐
Programiz
programiz.com › java-programming › library › string › indexof
Java String indexOf()
The indexOf() method returns the index of the first occurrence of the specified character/substring within the string. class Main { public static void main(String[] args) { String str1 = "Java is fun"; int result; // getting index of character 's'
Top answer
1 of 2
46

The complexity of Java's implementation of indexOf is O(m*n) where n and m are the length of the search string and pattern respectively.

What you can do to improve complexity is to use e.g., the Boyer-More algorithm to intelligently skip comparing logical parts of the string which cannot match the pattern.

2 of 2
26

java indexOf function complexity is O(n*m) where n is length of the text and m is a length of pattern
here is indexOf original code

   /**
     * Returns the index within this string of the first occurrence of the
     * specified substring. The integer returned is the smallest value
     * <i>k</i> such that:
     * <blockquote><pre>
     * this.startsWith(str, <i>k</i>)
     * </pre></blockquote>
     * is <code>true</code>.
     *
     * @param   str   any string.
     * @return  if the string argument occurs as a substring within this
     *          object, then the index of the first character of the first
     *          such substring is returned; if it does not occur as a
     *          substring, <code>-1</code> is returned.
     */
    public int indexOf(String str) {
    return indexOf(str, 0);
    }

    /**
     * Returns the index within this string of the first occurrence of the
     * specified substring, starting at the specified index.  The integer
     * returned is the smallest value <tt>k</tt> for which:
     * <blockquote><pre>
     *     k &gt;= Math.min(fromIndex, this.length()) && this.startsWith(str, k)
     * </pre></blockquote>
     * If no such value of <i>k</i> exists, then -1 is returned.
     *
     * @param   str         the substring for which to search.
     * @param   fromIndex   the index from which to start the search.
     * @return  the index within this string of the first occurrence of the
     *          specified substring, starting at the specified index.
     */
    public int indexOf(String str, int fromIndex) {
        return indexOf(value, offset, count,
                       str.value, str.offset, str.count, fromIndex);
    }

    /**
     * Code shared by String and StringBuffer to do searches. The
     * source is the character array being searched, and the target
     * is the string being searched for.
     *
     * @param   source       the characters being searched.
     * @param   sourceOffset offset of the source string.
     * @param   sourceCount  count of the source string.
     * @param   target       the characters being searched for.
     * @param   targetOffset offset of the target string.
     * @param   targetCount  count of the target string.
     * @param   fromIndex    the index to begin searching from.
     */
    static int indexOf(char[] source, int sourceOffset, int sourceCount,
                       char[] target, int targetOffset, int targetCount,
                       int fromIndex) {
    if (fromIndex >= sourceCount) {
            return (targetCount == 0 ? sourceCount : -1);
    }
        if (fromIndex < 0) {
            fromIndex = 0;
        }
    if (targetCount == 0) {
        return fromIndex;
    }

        char first  = target[targetOffset];
        int max = sourceOffset + (sourceCount - targetCount);

        for (int i = sourceOffset + fromIndex; i <= max; i++) {
            /* Look for first character. */
            if (source[i] != first) {
                while (++i <= max && source[i] != first);
            }

            /* Found first character, now look at the rest of v2 */
            if (i <= max) {
                int j = i + 1;
                int end = j + targetCount - 1;
                for (int k = targetOffset + 1; j < end && source[j] ==
                         target[k]; j++, k++);

                if (j == end) {
                    /* Found whole string. */
                    return i - sourceOffset;
                }
            }
        }
        return -1;
    }

you can simply implements the KMP algorithm without using of indexOf Like this

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.Scanner;


public class Main{
    int failure[];
    int i,j;
    BufferedReader in=new BufferedReader(new InputStreamReader(System.in));
    PrintWriter out=new PrintWriter(System.out);
    String pat="",str="";
    public Main(){
            try{

            int patLength=Integer.parseInt(in.readLine());
            pat=in.readLine();
            str=in.readLine();
            fillFailure(pat,patLength);
            match(str,pat,str.length(),patLength);
            out.println();
            failure=null;}catch(Exception e){}

        out.flush();
    }
    public void fillFailure(String pat,int patLen){
        failure=new int[patLen];
        failure[0]=-1;
        for(i=1;i<patLen;i++){
            j=failure[i-1];
            while(j>=0&&pat.charAt(j+1)!=pat.charAt(i))
                j=failure[j];
            if(pat.charAt(j+1)==pat.charAt(i))
                failure[i]=j+1;
            else
                failure[i]=-1;
        }
    }
    public void match(String str,String pat,int strLen,int patLen){
        i=0;
        j=0;
        while(i<strLen){
            if(str.charAt(i)==pat.charAt(j)){
                i++;
                j++;
                if(j==patLen){
                    out.println(i-j);
                    j=failure[j-1]+1;
                }
            } else if (j==0){
                    i++;
            }else{
                j=failure[j-1]+1;
            }

        }
    }
    public static void main(String[] args) {
        new Main();
    }
}
Top answer
1 of 6
1

If you don't know what a method does, then the solution is to go look at what it does. For example, the java documentation will tell you that

public int indexOf(int ch)

Returns the index within this string of the first occurrence of the specified character

In either case, if no such character occurs in this string, then -1 is returned.

How you're using it is not necessarily wrong, considering how the method returns -1 if the character wasn't found. But if you want to check how many vowels there are in a word that the user enters, it wouldn't be right to check whether the word they entered is in the string of vowels.

2 of 6
1

Here is what the indexOf method does

string.indexOf(searchvalue,start)

Parameters

searchvalue : Required. The string to search for 
start       : Optional. Default 0. At which position to start the search

Return Value

Number : The position where the specified searchvalue occurs for the first time, or -1 if it never occurs

In simple terms, the index of method checks the first occurence of the value passed to it from the start position(if specified) and returns the position at which the value was first encountered in the string.

eg.

String s = "AEIOUaeiou";
s.indexOf("a");     //This would get a value of 5.
s.indexOf("v");     //This would get a value of -1, since it doesn't have the character v

To answer your questions,

  1. You can directly declare the scanner as private and use it in the entire program

    `private static Scanner input = new Scanner(System.in);`
    
  2. you can write a method that receives the String input by the user and then checks if the String contains any of the vowels. You can use indexOf or contains methods to check for the each vowel using the indexOf method.

  3. Already described above.

  4. A better way to do it would be as follows.

public class vowelCounter{

    public static void main (String[] args) {
      Scanner keyboard = new Scanner (System.in); // No need to declare it as global. You use it only once.
      System.out.println ("Enter word : ");   //Prompt the user to enter a word    
      String input = keyboard.nextLine ();  //Fetch the word that the user enters into a String 
      System.out.println ("This word has" + countVowel (input)); // Pass the string to the method to check if it has vowels.
    }

   private static int countVowel (String a) {
     int count = 0;
     String s =  a.toLowerCase ();    // convert the string to lower case so that you only have to check for the lower case characters
    // Here you would need to check the number of times each vowel exists in the String and incremenet the count everytime.
    return count;
   }  
}
🌐
TechVidvan
techvidvan.com › tutorials › string-indexof-method-in-java
Java String indexOf() Method with Examples - TechVidvan
May 6, 2025 - The indexof() method searches the supplied Substring beginning at the beginning of the string.
🌐
Udemy
blog.udemy.com › home › it & development › software development › understanding the java string indexof method
Understanding the Java String IndexOf Method - Udemy Blog
April 14, 2026 - The Java string indexOf method is a function that is used to get the integer value of a particular index of String type object, based on a criteria specified in the parameters of the IndexOf method.