For working professionals
For fresh graduates
More
6. JDK in Java
7. C++ Vs Java
16. Java If-else
18. Loops in Java
20. For Loop in Java
46. Packages in Java
53. Java Collection
56. Generics In Java
57. Java Interfaces
60. Streams in Java
63. Thread in Java
67. Deadlock in Java
74. Applet in Java
75. Java Swing
76. Java Frameworks
78. JUnit Testing
81. Jar file in Java
82. Java Clean Code
86. Java 8 features
87. String in Java
93. HashMap in Java
98. Enum in Java
101. Hashcode in Java
105. Linked List in Java
109. Array Length in Java
111. Split in java
112. Map In Java
115. HashSet in Java
118. DateFormat in Java
121. Java List Size
122. Java APIs
128. Identifiers in Java
130. Set in Java
132. Try Catch in Java
133. Bubble Sort in Java
135. Queue in Java
142. Jagged Array in Java
144. Java String Format
145. Replace in Java
146. charAt() in Java
147. CompareTo in Java
151. parseInt in Java
153. Abstraction in Java
154. String Input in Java
156. instanceof in Java
157. Math Floor in Java
158. Selection Sort Java
159. int to char in Java
164. Deque in Java
172. Trim in Java
173. RxJava
174. Recursion in Java
175. HashSet Java
177. Square Root in Java
190. Javafx
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.
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.
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)
Also check: StringBuffer and StringBuilder Difference in Java
Let's break down the parameters used in the substring method:
Example:
String str = "Substring";
System.out.println(str.substring(3, 6));
Output:
str
Must explore: StringBuilder Class in Java
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.
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.
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.
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.
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
The substring method is widely used in real-world Java applications. Some practical uses include:
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.
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.
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.
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.
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.
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().
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.
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.
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.
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.
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.
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.
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.
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.
Take the Free Quiz on Java
Answer quick questions and assess your Java knowledge
Author
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.