Tutorial

Java String substring() Method Examples

Published on August 3, 2022
Default avatar

By Pankaj

Java String substring() Method Examples

While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial.

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

java string substring, substring in java Java String substring method is overloaded and has two variants.

  1. 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.
  2. 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

  1. 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
  2. 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() <= 1) {
			return true;
		}
		String first = str.substring(0, 1);
		String last = str.substring(str.length() - 1);
		if (!first.equals(last))
			return false;
		else
			return checkPalindrome(str.substring(1, str.length() - 1));
	}
}

Here we are checking if the first letter and the last letter is the same or not. If they are not the same, return false. Otherwise, call the method again recursively passing the substring with the first and last letter removed.

You can checkout more string examples from our GitHub Repository.

Reference: Oracle API Doc

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

Learn more about us


About the authors
Default avatar
Pankaj

author

Still looking for an answer?

Ask a questionSearch for more help

Was this helpful?
 
JournalDev
DigitalOcean Employee
DigitalOcean Employee badge
June 13, 2017

Hello Pankaj I want to understand negative indexing in strings, If it starts from -1 at the end of the string, it should go on -1,-2,-3 so on from right to left.what does 0th index represent then? I don’t understand the 3rd example here. I looked it up but haven’t found anything useful so far. ex: var str = ‘The morning is upon us.’; str.slice(-3); // returns ‘us.’ str.slice(-3, -1); // returns ‘us’ str.slice(0, -1); // returns 'The morning is upon us’1234

- Bindu Yadav

    Try DigitalOcean for free

    Click below to sign up and get $200 of credit to try our products over 60 days!

    Sign up

    Join the Tech Talk
    Success! Thank you! Please check your email for further details.

    Please complete your information!

    Get our biweekly newsletter

    Sign up for Infrastructure as a Newsletter.

    Hollie's Hub for Good

    Working on improving health and education, reducing inequality, and spurring economic growth? We'd like to help.

    Become a contributor

    Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.

    Welcome to the developer cloud

    DigitalOcean makes it simple to launch in the cloud and scale up as you grow — whether you're running one virtual machine or ten thousand.

    Learn more
    DigitalOcean Cloud Control Panel