beginnersbook.com

  • Home
  • All Tutorials
    • Learn Servlet
    • Learn JSP
    • Learn JSTL
    • Learn C
    • Learn C++
    • Learn MongoDB
    • Learn XML
    • Learn Python
    • Learn Perl
    • Learn Kotlin
  • Core Java
  • OOPs
  • Collections
  • Java I/O
  • JSON
  • DBMS

Java – String substring() Method example

By Chaitanya Singh | Filed Under: String handling

Method substring() returns a new string that is a substring of given string. Java String substring() method is used to get the substring of a given string based on the passed indexes. There are two variants of this method. In this guide, we will see how to use this method with the help of examples.

String substring() method variants

There are two ways we can use the substring() method –

1. When we pass only the starting index:

String substring(int beginIndex)

Returns the substring starting from the specified index i.e beginIndex and extends to the character present at the end of the string. For example – "Chaitanya".substring(2) would return "aitanya". The beginIndex is inclusive, that is why the character present at the index 2 is included in the substring. This method throws IndexOutOfBoundsException If the beginIndex is less than zero or greater than the length of String (beginIndex<0||> length of String).

2. When we pass both the indexes, starting index and end index:

String substring(int beginIndex, int endIndex)

Returns a new string that is a substring of this string. 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. In other words you can say that beginIndex is inclusive and endIndex is exclusive while getting the substring.

For example – "Chaitanya".substring(2,5) would return "ait". It throws IndexOutOfBoundsException If the beginIndex is less than zero OR beginIndex > endIndex OR endIndex is greater than the length of String.

Java String substring() example

Now that we understand the basics of substring() method, lets take an example to understand the usage of this method.

Here we have a string str and we are finding out the substring of this string using the substring() method.

public class SubStringExample{
   public static void main(String args[]) {
       String str= new String("quick brown fox jumps over the lazy dog");
       System.out.println("Substring starting from index 15:");
       System.out.println(str.substring(15));
       System.out.println("Substring starting from index 15 and ending at 20:");
       System.out.println(str.substring(15, 20));
   }
}

Output:

Substring starting from index 15:
 jumps over the lazy dog
Substring starting from index 15 and ending at 20:
 jump

Note: Many peoples are confused that the returned substring in the second method call should be jumps instead of jump, this is because the returned substring length should be endIndex-beginIndex, in our example beginIndex is 15 and endIndex is 20, thus the length of returned substring should be 20-15 = 5. The correct answer is ” jump” because there is a space before the jump so the length of substring ” jump” is 5 (including the space).
To further avoid confusion, I am sharing an another example of this method which is easy to follow.

Another example of String substring() method

public class JavaExample{
   public static void main(String args[]) {
	String mystring = new String("Lets Learn Java");
	/* The index starts with 0, similar to what we see in the arrays
	 * The character at index 0 is s and index 1 is u, since the beginIndex
	 * is inclusive, the substring is starting with char 'u'
	 */
	System.out.println("substring(1):"+mystring.substring(1));
		
	/* When we pass both beginIndex and endIndex, the length of returned
	 * substring is always endIndex - beginIndex which is 3-1 =2 in this example
	 * Point to note is that unlike beginIndex, the endIndex is exclusive, that is 
	 * why char at index 1 is present in substring while the character at index 3 
	 * is not present.
	 */
	System.out.println("substring(1,3):"+mystring.substring(1,3));
   }
}

Output:
Java String substring method example
Reference: Javadoc substring()

❮ PreviousNext ❯

Comments

  1. David says

    March 8, 2016 at 4:50 PM

    I think the second result is “jumps”

    Reply
    • Laila says

      September 28, 2016 at 4:42 PM

      I thought it would be ” jump” if we consider the space before the word “jumps” as a character.
      As its explained above the example , “chaitanya”.substring(2,5) and the result is “a(2)i(3)t(4)”, so the fifth character isn’t taken ?

      Reply
    • Rana Imran says

      October 30, 2016 at 12:37 PM

      also count space ,secondly 20 end at “s”,so java show less one character.so result is jump.
      Example:
      abc
      012
      (0,1) show just a exclusive end point.

      Reply
    • Cyril says

      November 7, 2016 at 2:00 PM

      No it’s correct the result is ” jump” with a space before

      Reply
    • gorge says

      December 24, 2016 at 3:33 PM

      bad example =(
      the space just so hard to see, such misleading

      Reply
    • Anony-mouse says

      January 1, 2019 at 7:33 PM

      When using .substring(x,y), the x index is inclusive and y index is exclusive, therefore it is “jump”.

      Reply
  2. Abhinabo says

    January 30, 2017 at 2:16 PM

    had forgotten the concept
    the example helped alot, thanks!

    Reply
  3. pyguillemet says

    January 20, 2018 at 4:13 AM

    To sum up :
    – O base index
    – Range [beginIndex, endIndex[
    – Ex: “abc 123”.substring(1,5) => “bc 1”

    Reply
  4. iHadTo says

    July 7, 2018 at 7:16 AM

    1) the result is not very helpful, the space before the “jumps” is confusing
    2) when you are making tutorials, you should give more detailed explanations. . When you say “starting from index 15 and ending at 20” , most people will assume that it includes the character at index 20 as well. The main thing that needs to be said about substring is that the boundaries are [ beginIndex, endIndex ) which means the first index is included, the second isn’t.
    Still appreciate your efforts but sometimes beginners need really simple explanations

    Reply
  5. vijayasree says

    July 16, 2018 at 12:02 PM

    Hello…Good example,it counts the spaces too and gives the result.

    Reply
  6. HA says

    November 29, 2018 at 8:28 PM

    may want to review the java documentation (the key here is how the end index is handled: as value-1, or in other words “exclusively”):

    public String substring(int beginIndex, int endIndex)

    Returns a new string that is a substring of this string. 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.
    Examples:
    “hamburger”.substring(4, 8) returns “urge”
    “smiles”.substring(1, 5) returns “mile”
    Parameters:
    beginIndex – the beginning index, inclusive.
    endIndex – the ending index, exclusive.
    Returns:
    the specified substring.
    Throws:
    IndexOutOfBoundsException – if the beginIndex is negative, or endIndex is larger than the length of this String object, or beginIndex is larger than endIndex.

    see: https://docs.oracle.com/javase/7/docs/api/java/lang/String.html#substring(int,%20int)

    Reply
  7. ejthayer says

    December 4, 2018 at 7:51 PM

    Most computer languages for many years used a start index and a length as the parameters. For some reason Java decided to use a start and end index that actually returns the characters from start to end – 1. Personally I think this is a horrible implementation of this command, seems like a massive brain stress by the creators of Java. Now that Java is so popular there are 2 major ways this function works now that this stupid implementation has been repeated in several other languages.

    Reply
  8. Khushi Mehrotra says

    January 2, 2019 at 2:37 PM

    Good helped a lot

    Reply

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Java Tutorials

  • Learn Java
  • OOPs Concepts
  • Java Collections

Java String

  • Java String

Java String Methods

  • String charAt()
  • String compareTo()
  • String compareToIgnoreCase()
  • String contains()
  • String concat()
  • substring
  • String valueOf()
  • String startsWith()
  • String equals()
  • String format()
  • String endsWith()
  • String indexOf()
  • String lastIndexOf()
  • String length()
  • String replace()
  • String split()
  • String trim()
  • String intern()
  • String isEmpty()
  • String matches()
  • String regionMatches()
  • String contentEquals()
  • String toCharArray()
  • String getBytes()
  • String join()
  • String getChars()
  • String copyValueOf()

Recently Added..

  • JSON Tutorial
  • Java Regular Expressions Tutorial
  • Java Enum Tutorial
  • Java Annotations Tutorial

Copyright © 2012 – 2021 BeginnersBook . Privacy Policy . Sitemap