Mastering strings in Java often involves working with substrings, which are portions of a larger string. The String class in Java provides a number of methods to extract substrings. Let's dive into Java substring examples to better understand how to manipulate strings.

The most common way to extract a substring in Java is by using the substring method. It requires the start and end indices of the substring you want to extract.

Extracting Substrings Using Indexes
The substring method with two parameters begins extracting the substring from the start index up to, but not including, the end index.

Here's a simple example:
Extracting a Substring Up to a Specific Length

Let's say you have a string String text = "Hello, World!" and you want to extract the first five characters. You would use text.substring(0, 5), which returns "Hello".
The start index 0 indicates the very first character of the string. The end index 5 indicates the index after the last character you want. So, this substring method will return everything from the first character up to, but not including, the sixth character.
Extracting a Substring Starting From an Index

If you want to extract a substring starting from a specific index all the way to the end of the string, you can use the substring method with only one parameter.
For example, to extract everything from the sixth character onward, you would use text.substring(5). This returns "World!" starting from the sixth character.
Other Useful Substring Methods

Java offers other convenient methods for handling substrings. Let's explore a couple of them.
Using lastIndexOf to Determine Substring Limits










![[Solved] How to count Vowels and Consonants in Java String Word? Example](https://i.pinimg.com/originals/9e/34/94/9e3494d47f9aeda7562f34f97430ad70.png)








The lastIndexOf method helps when you're not sure of the index you want. It searches backward through the string for the specified character or substring and returns its index.
For instance, finding the comma in the text variable above can be done with text.lastIndexOf(','). This method returns the index 2, since Java uses zero-based indexing.
You can use this with substring to extract a substring starting from a specific character, like this: text.substring(text.lastIndexOf(',') + 1). This returns " World!" starting from the comma.
Using replace to Modify Substrings
The replace method lets you replace a substring with another string. This is useful when you want to change a portion of a string. For example, if you want to change "World" in text to "Java", you can use text.replace("World", "Java") which returns "Hello, Java!".
Understanding and practicing these substring methods will help you navigate string manipulation tasks in Java with ease. As you become more comfortable with these techniques, you'll find yourself quickly extracting and modifying substrings according to your needs. Happy coding!