Java String Indexing [In-Depth Tutorial]


Written By - Bashir Alam
Advertisement

In Java, strings are indexed using the zero-based index. This means that the first character in a string is at index 0, the second character is at index 1, and so on.

To access a specific character in a string, you can use the charAt() method, which takes an integer argument representing the index of the character you want to access. For example:

String str = "hello";
char c = str.charAt(0); // returns 'h'

You can also use square brackets to access a specific character in a string, just like you would with an array. For example:

String str = "hello";
char c = str[0]; // This will not work - you must use the charAt() method instead

Note that attempting to access an index that is out of bounds (i.e., greater than or equal to the length of the string) will result in a StringIndexOutOfBoundsException being thrown.

 

Java String Indexing

Java String indexing refers to the process of accessing individual characters within a string by their position or index. Each character in a string is assigned a unique index starting from 0 for the first character, 1 for the second character, and so on. Here we will now go through various examples to understand how the java string indexing works.

 

String Character Indexing in Java

To access an individual character in a string in Java, you can use the charAt() method, which takes an integer argument representing the index of the character to be accessed. For example:

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

        // indexing
        char firstChar = message.charAt(0);
        char thirdChar = message.charAt(2);

        // printing
        System.out.println(firstChar);
        System.out.println(thirdChar);
    }
}

Output:

H
l

In this example, the charAt() method is used to access the first and third characters of the message string by passing in their corresponding indexes.

Advertisement

 

String Length and Indexing in Java

The length of a string in Java can be obtained using the length() method, which returns the number of characters in the string. The length of a string can be used in conjunction with indexing to access the last character of a string. For example:

public class Main {
    public static void main(String[] args) {
        String message = "Hello, World";
        int length = message.length(); 
        char lastChar = message.charAt(length - 1); 

        // printing
        System.out.println(length);
        System.out.println(lastChar);
    }
}

Output:

12
d

In this example, the length() method is used to obtain the length of the message string, and the index of the last character is calculated by subtracting 1 from the length. The charAt() method is then used to access the last character of the string by passing in the calculated index.

 

String IndexOutOfBounds Exception in Java

When using indexing to access characters in a string in Java, it's important to be careful not to go out of bounds. If an index that is less than 0 or greater than or equal to the length of the string is used with the charAt() method, a StringIndexOutOfBoundsException will be thrown. For example:

public class Main {
    public static void main(String[] args) {
        String message = "Hello, World!";
        char outOfBoundsChar = message.charAt(20);
    }
}

Output:

Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 20
        at java.base/java.lang.StringLatin1.charAt(StringLatin1.java:47)
        at java.base/java.lang.String.charAt(String.java:693)
        at Main.main(Main.java:4)

In this example, the index 20 is greater than the length of the message string, so attempting to access the character at that index with the charAt() method results in a StringIndexOutOfBoundsException being thrown.

 

Java String Methods for Indexing

In addition to the charAt() method, Java provides several other methods that can be used to access and manipulate individual characters in a string. Here, we will go through some of the useful methods for indexing in Java programming language.

 

indexOf()

The indexOf() method returns the index of the first occurrence of a specified character or substring in a string. If the specified character or substring is not found in the string, the method returns -1.

Advertisement
public class Main {
    public static void main(String[] args) {
        String message = "Hello, World!";
        int index1 = message.indexOf('l'); 
        int index2 = message.indexOf("World"); 
        int index3 = message.indexOf('z');

        // printing
        System.out.println(index1);
        System.out.println(index2);
        System.out.println(index3);
    }
}

Output:

2
7
-1

In this example, the indexOf() method is used to find the index of the first occurrence of the character 'l', the substring "World", and the character 'z' in the message string.

 

lastIndexOf()

The lastIndexOf() method is similar to indexOf(), but it returns the index of the last occurrence of a specified character or substring in a string. If the specified character or substring is not found in the string, the method returns -1. For example:

public class Main {
    public static void main(String[] args) {
        String message = "Hello, World!";
        int index1 = message.lastIndexOf('l'); 
        int index2 = message.lastIndexOf("World"); 
        int index3 = message.lastIndexOf('z');

        // printing
        System.out.println(index1);
        System.out.println(index2);
        System.out.println(index3);
    }
}

Output:

10
7
-1

In this example, the lastIndexOf() method is used to find the index of the last occurrence of the character 'l', the substring "World", and the character 'z' in the message string.

 

substring()

The substring() method returns a substring of a string that starts at a specified index and extends to the end of the string, or to a specified index.

Advertisement
public class Main {
    public static void main(String[] args) {
        String message = "Hello, World!";
        String substring1 = message.substring(2);
        String substring2 = message.substring(2, 7);

        // printing
        System.out.println(substring1);
        System.out.println(substring2);
    }
}

Output:

llo, World!
llo,

In this example, the substring() method is used to obtain substrings of the message string that start at index 2 and extend to the end of the string, or to index 7.

 

Summary

Java string indexing describes the method of gaining access to specific characters within a string based on their location or index. The first character in a string in Java is indexed at position 0, the second at position 1, and so on. In this short article, we discussed how we can use the indexing of strings in Java programming language by solving various examples.

 

Further Reading

Java strings

 

Didn't find what you were looking for? Perform a quick search across GoLinuxCloud

If my articles on GoLinuxCloud has helped you, kindly consider buying me a coffee as a token of appreciation.

Buy GoLinuxCloud a Coffee

For any other feedbacks or questions you can either use the comments section or contact me form.

Thank You for your support!!

Leave a Comment