Java indexOf - yuriyni.com

Java indexOf. Tutorial and Examples

What is a indexOf?

The java indexOf() method of String class is used for getting a substring from the string.

public final class String extends Object implements Serializable, Comparable<String>, CharSequence, Constable, ConstantDesc

...

The String class represents character strings. All string literals in Java programs, such as "abc", are implemented as instances of this class.

Beginning with JDK 9, all of java.lang is part of the java.base module. The String class represents character strings. All string literals in Java programs, such as "abc", are implemented as instances of this class.

Java Platform, Standard Edition & Java Development Kit Version 16 API Specification
Module java.base
Package java.lang
Class String

Because String objects are immutable, whenever you want to modify a String, you must either copy it into a StringBuffer or StringBuilder, or use a String method that constructs a new copy of the string with your modifications complete.

Syntax #1 of String indexOf() method

public int indexOf​(int ch)
java 16 docs

It returns the index of the first occurrence of character ch in a given String. If a character with value ch occurs in the character sequence represented by this String object, then the index (in Unicode code units) of the first such occurrence is returned.

String indexOf Example #1

package com.yuriyni.java.base.java.lang;

public class IndexOfDemo {
    public static void main(String[] args) {

        String myStr = "Hello World";

        int index1= myStr.indexOf('W');
        int index2 = myStr.indexOf('X');

        System.out.println(index1);
        System.out.println(index2);
    }
}

Output

6
-1

Syntax #2 of String indexOf() method

public int indexOf​(int ch, int fromIndex)

Returns the index within this string of the first occurrence of the specified character, starting the search at the specified index.

java 16 docs

String indexOf Example #2

package com.yuriyni.java.base.java.lang;

public class IndexOfDemo {
    public static void main(String[] args) {

        String myStr = "Hello World";

        int index1= myStr.indexOf('W');
        int index2 = myStr.indexOf('X');

        int index3 = myStr.indexOf('o'  );
        
        //starting the search at the specified index.
        int index4 = myStr.indexOf('o',5 );

        System.out.println(index1);
        System.out.println(index2);

        System.out.println(index3);
        System.out.println(index4);
    }
}

Output

6
-1
4
7

Here are some more examples of how String charAt can be used:

String myStr = "Hello World";
int index5 = myStr.indexOf("World"  );
System.out.println(index5);

Output

6

Download source code

https://github.com/yuriynee/learning-java-with-yuriy-ni