0
0
JavaHow-ToBeginner · 3 min read

How to Find Substring in Java: Syntax and Examples

In Java, you can find a substring using the indexOf method which returns the position of the substring or -1 if not found. Alternatively, use contains to check if a substring exists, returning a boolean value.
📐

Syntax

The main methods to find a substring in Java are:

  • int indexOf(String substring): Returns the starting index of the substring or -1 if not found.
  • boolean contains(CharSequence sequence): Returns true if the substring exists, otherwise false.
java
String str = "Hello, world!";
int position = str.indexOf("world");
boolean exists = str.contains("Hello");
💻

Example

This example shows how to find the position of a substring and check if it exists in a string.

java
public class SubstringExample {
    public static void main(String[] args) {
        String text = "Welcome to Java programming!";
        String search = "Java";

        int index = text.indexOf(search);
        if (index != -1) {
            System.out.println("Substring '" + search + "' found at index: " + index);
        } else {
            System.out.println("Substring not found.");
        }

        boolean contains = text.contains(search);
        System.out.println("Does the text contain '" + search + "'? " + contains);
    }
}
Output
Substring 'Java' found at index: 11 Does the text contain 'Java'? true
⚠️

Common Pitfalls

Common mistakes when finding substrings in Java include:

  • Not checking if indexOf returns -1 before using the index.
  • Confusing indexOf with contains: indexOf returns an index, contains returns a boolean.
  • Case sensitivity: these methods are case sensitive, so "java" and "Java" are different.
java
String text = "Hello World";

// Wrong: Using index without checking
int pos = text.indexOf("world");
System.out.println("Position: " + pos); // Outputs -1, but no check

// Right: Check before using
if (pos != -1) {
    System.out.println("Found at: " + pos);
} else {
    System.out.println("Not found");
}
Output
Position: -1 Not found
📊

Quick Reference

MethodDescriptionReturn TypeExample
indexOf(String)Finds starting index of substringintstr.indexOf("abc")
contains(CharSequence)Checks if substring existsbooleanstr.contains("abc")
substring(int, int)Extracts substring by index rangeStringstr.substring(2,5)

Key Takeaways

Use indexOf to get the position of a substring; it returns -1 if not found.
Use contains to check if a substring exists; it returns true or false.
Always check indexOf result before using it to avoid errors.
Remember substring search is case sensitive in Java.
Use substring method to extract parts of a string by index.