Java String substring[] method returns the substring of this string. This method always returns a new string and the original string remains unchanged because String is immutable in Java.
Java String substring[] Methods
substring[int beginIndex]
: This method returns a new string that is a substring of this string. The substring begins with the character at the specified index and extends to the end of this string.substring[int beginIndex, int endIndex]
: The substring begins at the specified beginIndex and extends to the character at index endIndex - 1. Thus the length of the substring is [endIndex - beginIndex].
String substring[] Method Important Points
- Both the string substring methods can throw
IndexOutOfBoundsException
if any of the below conditions met.- if the beginIndex is negative
- endIndex is larger than the length of this String object
- beginIndex is larger than endIndex
- beginIndex is inclusive and endIndex is exclusive in both substring methods.
Java String substring[] Example
Here is a simple program for the substring in java.
package com.journaldev.util;
public class StringSubstringExample {
public static void main[String[] args] {
String str = "www.journaldev.com";
System.out.println["Last 4 char String: " + str.substring[str.length[] - 4]];
System.out.println["First 4 char String: " + str.substring[0, 4]];
System.out.println["website name: " + str.substring[4, 14]];
}
}
Output of the above substring example program is:
Last 4 char String: .com
First 4 char String: www.
website name: journaldev
Checking Palindrome using substring[] Method
We can use the substring[] method to check if a String is a palindrome or not.
package com.journaldev.util;
public class StringPalindromeTest {
public static void main[String[] args] {
System.out.println[checkPalindrome["abcba"]];
System.out.println[checkPalindrome["XYyx"]];
System.out.println[checkPalindrome["871232178"]];
System.out.println[checkPalindrome["CCCCC"]];
}
private static boolean checkPalindrome[String str] {
if [str == null]
return false;
if [str.length[]