How do I get a part or a substring of a string?

The following code snippet demonstrates how to get some part from a string. To do this we use the String.substring() method. The first substring() method take a single parameter, beginIndex, the index where substring start. This method will return part of string from the beginning index to the end of the string.

The second method, substring(int beginIndex, int endIndex), takes the beginning index, and the end index of the substring operation. The index of this substring() method is a zero-based index, this means that the first character in a string start at index 0.

package org.kodejava.lang;

public class SubstringExample {
    public static void main(String[] args) {
        // This program demonstrates how we can take some part of a string 
        // or what we called as substring. Java String class provides 
        // substring method with some overloaded parameter.
        String sentence = "The quick brown fox jumps over the lazy dog";

        // The first substring method with single parameter beginIndex 
        // will take some part of the string from the beginning index 
        // until the last character in the string.
        String part = sentence.substring(4);
        System.out.println("Part of sentence: " + part);

        // The second substring method take two parameters, beginIndex 
        // and endIndex. This method returns the substring start from 
        // beginIndex to the endIndex.
        part = sentence.substring(16, 30);
        System.out.println("Part of sentence: " + part);

This code snippet print out the following result:

Part of sentence: quick brown fox jumps over the lazy dog
Part of sentence: fox jumps over

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.