Extracting substrings

Java:
Extracting substrings

How to:

Extracting a substring in Java is straightforward using the substring method. Here’s how you do it:

public class SubstringExample {
    public static void main(String[] args) {
        String fullString = "Hello, World!";

        // Extract from index 7 to the end of the string
        String sub1 = fullString.substring(7);
        System.out.println(sub1); // Output: World!

        // Extract from index 0 to index 4 (5 is not included)
        String sub2 = fullString.substring(0, 5);
        System.out.println(sub2); // Output: Hello
    }
}

Remember: In Java, string indexing starts at 0.

Deep Dive

The substring method has been around since the early days of Java, providing a simple way to get parts of a string. In older versions of Java, substring would share the original character array, which could lead to memory leaks if the original string was large and the substring was kept for a long time. Since Java 7 update 6, substring creates a new string, so the old one can be garbage-collected if not used elsewhere.

Also, before reaching out to substring, consider if you can use split, replace, or regex utilities for more complex scenarios. Internally, substring in Java uses methods from the String class that copy arrays—efficient, but not something you have direct control over.

See Also

Whether it’s for a quick trim or a complex data extraction, the functions you need are there. Keep your toolkit well-understood and ready to go.