View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All

Substring in Java: A Beginner’s Guide with Syntax, Examples & Use Cases

Updated on 14/05/20255,751 Views

In Java programming, handling strings is a regular part of development. Whether you're extracting part of a name, filtering text, or parsing user inputs, the ability to work with string sections is essential. That’s where the substring() method in Java becomes valuable. It lets you extract a portion of a string based on specified indices.

This blog covers what substring in Java is, how it works, its syntax, use cases, exception handling, and examples to ensure you understand every angle of this topic. 

By the end, you'll be comfortable using substring in real-world coding tasks. Software engineering courses can help strengthen your string handling skills and Java fundamentals.

What is Substring in Java?

In Java, a substring is a portion of a string extracted from a larger string using index values. Java provides the substring() method in the String class to achieve this. You can extract characters starting from a specific index to the end of the string, or between two indices.

Think of it like cutting a slice out of a loaf of bread — you specify the starting and (optionally) ending slice.

String str = "JavaProgramming";
String sub = str.substring(0, 4);
System.out.println(sub);

Output:

Java

Explanation: The substring starts at index 0 and ends before index 4.

Enhance your abilities through these best-in-class courses/certifications.

Syntax of substring() Method

Understanding the syntax is crucial before using substring. Java provides two method signatures for substring:

public String substring(int beginIndex)
public String substring(int beginIndex, int endIndex)
  • beginIndex: Starting index (inclusive)
  • endIndex: Ending index (exclusive)
  • Returns a new string based on the range provided.
  • If indices are invalid, it throws StringIndexOutOfBoundsException.

Also check: StringBuffer and StringBuilder Difference in Java

Parameters in substring()

Let's break down the parameters used in the substring method:

  • beginIndex: Index of the first character to include.
  • endIndex (optional): Index before which to stop (excluded from result).
  • Both indices should be within bounds: 0 <= beginIndex <= endIndex <= string.length().

Example:

String str = "Substring";
System.out.println(str.substring(3, 6));

Output:

str

Must explore: StringBuilder Class in Java

Return Type of substring()

The return type of the substring() method is always a String. The method returns a new string containing the specified character range. It does not modify the original string (since strings are immutable in Java).

String original = "Immutable";
String newStr = original.substring(0, 4);
System.out.println(newStr);

Output:

Immu

Explanation: The original string remains unchanged.

Exceptions in substring()

If you pass an invalid range in substring, Java throws a StringIndexOutOfBoundsException.

Here’s how it looks:

String str = "Exception";
System.out.println(str.substring(5, 15)); // Invalid

Output:

Exception in thread "main" java.lang.StringIndexOutOfBoundsException: begin 5, end 15, length 9

Explanation: The end index exceeds the string's length.

Example 1: substring(int beginIndex)

This version extracts the string from the given index to the end of the string.

String word = "Beginner";
System.out.println(word.substring(3));

Output:

inner

Explanation: It starts from index 3 and continues to the end of the string.

Example 2: substring(int beginIndex, int endIndex)

This version extracts characters from beginIndex (inclusive) to endIndex (exclusive).

String text = "Programming";
System.out.println(text.substring(0, 6));

Output:

Progra

Explanation: It extracts characters from index 0 to 5.

Case Sensitivity and Substring

Strings in Java are case-sensitive, and substring behaves accordingly. This means "Java" and "java" are treated as different values, even in extraction.String mix = "JavaIsFun";

System.out.println(mix.substring(0, 4));

Output:

Java

Use Cases of Substring in Real Applications

The substring method is widely used in real-world Java applications. Some practical uses include:

  • Extracting domain names from email addresses
  • Parsing data from formatted strings
  • Displaying snippets of user-generated content
  • Handling tokens in URLs or APIs

Example:

String email = "user@example.com";
String domain = email.substring(email.indexOf("@") + 1);
System.out.println(domain);

Output:

example.com

Explanation: Extracts everything after the '@' symbol.

Performance Tip: Substring and Memory

In older Java versions, substring shared the same memory as the original string. However, from Java 7 update 6 onward, this changed. Now, substring creates a new character array, reducing memory leaks but slightly increasing memory usage for many substrings.

For large-scale string manipulations, consider using StringBuilder.

Conclusion

The substring() method in Java is simple yet powerful. It helps you manipulate text by extracting specific parts of strings. By understanding how it works, its syntax, and common use cases, you can avoid common pitfalls like index errors and use it more effectively in your Java programs.

Practicing with real-world string data will make your understanding stronger. You’ll find this method extremely helpful in projects involving text processing, APIs, and file handling.

FAQs

1. Can substring() return an empty string in Java?

Yes, if the beginIndex and endIndex are the same, substring returns an empty string. It doesn't throw an error because technically you're extracting zero characters. This is often used to validate input or split strings safely without causing exceptions.

2. Is substring() inclusive or exclusive in Java?

The substring() method is inclusive of the beginIndex and exclusive of the endIndex. So, if you use substring(2, 5), it will include the character at index 2 and exclude the one at index 5. This can help avoid off-by-one errors.

3. Can we use substring() on null strings?

No, calling substring() on a null string will throw a NullPointerException. To avoid this, always check if the string is not null using a conditional statement or Objects.requireNonNull() before applying any string operation like substring().

4. How does substring() behave with white spaces?

The substring() method treats white spaces as valid characters. If your substring range includes spaces, they will be returned in the result. It does not trim spaces unless you explicitly call the trim() method after extracting the substring.

5. Does substring() modify the original string?

No, Java strings are immutable. Using substring() creates a new string without altering the original one. This ensures that the source string remains unchanged, which is a key feature of how Java handles string objects securely and efficiently.

6. How can I get the last N characters using substring()?

To get the last N characters, use substring(string.length() - N). Make sure the string's length is greater than or equal to N to avoid exceptions. This is helpful in cases like masking sensitive information or formatting output strings.

7. Can we chain substring() with other string methods?

Yes, substring can be chained with other string methods like toUpperCase(), trim(), or contains(). For example: str.substring(0, 4).toUpperCase(). Chaining improves readability and makes string manipulation concise and expressive in Java.

8. How is substring() different from split() in Java?

substring() extracts a part of the string based on index positions. In contrast, split() breaks a string into an array using a delimiter like a comma or space. They serve different purposes but can be used together for complex string parsing.

9. Can substring() be used in Java Streams?

Yes, you can use substring inside Java Streams while mapping elements. For instance, in a list of strings, you can apply .map(str -> str.substring(0, 3)) to extract substrings. This is useful for processing collections functionally and efficiently.

10. How does substring() work with Unicode characters?

substring() in Java works on Unicode-compliant UTF-16 code units. If your string includes emojis or accented characters, they may be represented by surrogate pairs. Improper indexing may break such characters, so be cautious with multi-byte characters.

11. Is substring() faster than other string operations?

substring() is relatively fast for small or moderate-sized strings. However, excessive or nested use can impact performance, especially in loops. For heavy string processing, consider alternatives like StringBuilder, especially when frequent modifications are involved.

image

Take the Free Quiz on Java

Answer quick questions and assess your Java knowledge

right-top-arrow
image
Join 10M+ Learners & Transform Your Career
Learn on a personalised AI-powered platform that offers best-in-class content, live sessions & mentorship from leading industry experts.
advertise-arrow

Free Courses

Explore Our Free Software Tutorials

Disclaimer

1.The above statistics depend on various factors and individual results may vary. Past performance is no guarantee of future results.

2.The student assumes full responsibility for all expenses associated with visas, travel, & related costs. upGrad does not provide any a.