BeginnersBook

  • Home
  • Java
    • Java OOPs
    • Java Collections
    • Java Examples
  • C
    • C Examples
  • C++
    • C++ Examples
  • DBMS
  • Computer Network
  • Python
    • Python Examples
  • More…
    • jQuery
    • Kotlin
    • WordPress
    • SEO
    • JSON
    • JSP
    • JSTL
    • Servlet
    • MongoDB
    • XML
    • Perl

Java String substring() Method with examples

Last Updated: September 17, 2022 by Chaitanya Singh | Filed Under: java

The substring() method is used to get a substring from a given string. This is a built-in method of string class, it returns the substring based on the index values passed to this method. For example: “Beginnersbook”.substring(9) would return “book” as a substring.

This method has two variants, one is where you just specify the start index and in the other variant, you can specify both start and end indexes.

Java substring method

String substring() method variants

There are two variants of substring method in Java.

1. Only the beginIndex:

String substring(int beginIndex)

Returns the substring starting from the specified index beginIndex till the last character 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. Both beginIndex and endIndex:

String substring(int beginIndex, int endIndex)

Returns a substring starting from specified beginIndex till the character present at 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() examples

Now that we understand the basics of substring() method, let’s take few examples to understand the usage of this method.

1. Basic substring example demonstrates both the variants of this method

Before we start to see some interesting substring method examples, let’s start with a simple example that demonstrates the usage of this method.

public class JavaExample{
  public static void main(String args[]) {
    String str= new String("WelcomeHome!");
    System.out.print("Substring starting from index 7: ");
    System.out.println(str.substring(7));
    System.out.print("Substring from beginIndex 3 till endIndex 7: ");
    System.out.println(str.substring(3, 7));
  }
}

Output:
Java substring example output
Note: The returned substring length is always endIndex-beginIndex, In our example beginIndex is 3 and endIndex is 7, thus the length of returned substring should be 7-3 = 4.

2. Get a substring between two delimiters

In this program, we are using indexOf() and substring() method of Java String class.

We are finding the indexes of delimiters in the string using indexOf() method. Once we have the indexes of delimiters, we are calling substring method to find the substring between these delimiters.

Note: The method is called like this: substring(start + 1, end), here start index is +1 because, we want to get the substring after the delimiter position, however the end index is not +1 because end index is not inclusive in substring method.

public class JavaExample{
  public static void main(String[] args){

    //given string
    String str = "Welcome to [BeginnersBook.com]";

    //we would like to get the substring between '[' and ']'
    int start = str.indexOf("[");
    int end = str.indexOf("]");

    String outStr = str.substring(start + 1, end);
    System.out.println(outStr);
  }
}

Output:

BeginnersBook.com

Similarly you can use the same logic to get the substring between two characters:

public class JavaExample{
  public static void main(String[] args){

    //input string
    String str = "abcdefg";

    //get the substring between two characters 'a' 'd'
    int start = str.indexOf('a');
    int end = str.lastIndexOf('d');

    String outStr = str.substring(start+1, end);
    System.out.println(outStr);
  }
}

Output:

bc

3. Get a substring between two given strings

This is another interesting example. Here we have a string and we want to get a substring between two strings “Beginners” and “com”. To do this, we have searched the index of first string using indexOf() and added the length of this string, this is because indexOf() gives the index of first character of the string but we want to start reading after the end of string “Beginners”.

Similarly, we found the starting index of second string “com” and get the substring between these indexes using substring method.

public class JavaExample{
  public static void main(String[] args){

    //input string
    String str = "Welcome to [BeginnersBook.com]";

    //get the substring between "Beginners" and "com"
    int start = str.indexOf("Beginners")+"Beginners".length();
    int end = str.lastIndexOf("com");

    String outStr = str.substring(start, end);
    System.out.println(outStr);
  }
}

Output:

Book.

4. Remove first and last character from a string

In this program, we are using substring() method to exclude first and last character from the string.

  • str.substring(1): This excludes first character as the index 0 character (first character) is excluded.
  • substring(0, str.length()-1): This excludes last character as the length() method returns the length of the string and when we provide str.length()-1 as the endIndex, it excludes last character.
public class JavaExample{
  public static void main(String args[]) {
    String str= new String("Pasta");
    System.out.print("Substring after removing first character: ");
    System.out.println(str.substring(1));
    System.out.print("Substring after removing last character: ");
    System.out.println(str.substring(0, str.length()-1));
  }
}

Output:
Substring after removing first and last character

❮ PreviousNext ❯

Top Related Articles:

  1. Java StringBuilder Class With Examples
  2. Java StringBuffer replace()
  3. Java String equals() and equalsIgnoreCase() Methods example
  4. Java StringBuilder offsetByCodePoints()
  5. Java StringBuffer subSequence()

Tags: Java-Strings

About the Author

I have 15 years of experience in the IT industry, working with renowned multinational corporations. Additionally, I have dedicated over a decade to teaching, allowing me to refine my skills in delivering information in a simple and easily understandable manner.

– Chaitanya

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
    • 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. vijayasree says

    July 16, 2018 at 12:02 PM

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

    Reply
  5. 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
  6. 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
  7. 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 Tutorial

Java Introduction

  • Java Index
  • Java Introduction
  • History of Java
  • Features of Java
  • C++ vs Java
  • JDK vs JRE vs JVM
  • JVM - Java Virtual Machine
  • First Java Program
  • Variables
  • Data Types
  • Operators

Java Flow Control

  • Java If-else
  • Java Switch-Case
  • Java For loop
  • Java while loop
  • Java do-while loop
  • Continue statement
  • break statement

Java Arrays

  • Java Arrays

OOPs Concepts

  • OOPs Concepts
  • Constructor
  • Java String
  • Static keyword
  • Inheritance
  • Types of inheritance
  • Aggregation
  • Association
  • Super Keyword
  • Method overloading
  • Method overriding
  • Overloading vs Overriding
  • Polymorphism
  • Types of polymorphism
  • Static and dynamic binding
  • Abstract class and methods
  • Interface
  • Abstract class vs interface
  • Encapsulation
  • Packages
  • Access modifiers
  • Garbage Collection
  • Inner classes
  • Static import
  • Static constructor

Java Exception Handling

  • Exception handling
  • Java try-catch
  • Java throw
  • Java throws
  • Checked and Unchecked Exceptions
  • Jav try catch finally
  • Exception Examples
  • Exception Propagation

Collections Framework

  • Collections in Java
  • Java ArrayList
  • Java LinkedList
  • Java Vector
  • Java HashSet
  • Java LinkedHashSet
  • Java TreeSet
  • Java HashMap
  • Java TreeMap
  • Java LinkedHashMap
  • Java Queue
  • Java PriorityQueue
  • Java Deque
  • Comparable interface
  • Comparator interface
  • Collections Interview Questions

MORE ...

  • Java Scanner Class
  • Java 8 Features
  • Java 9 Features
  • Java Conversion
  • Java Date
  • Java Multithreading
  • Java I/O
  • Java Serialization
  • Java Regex
  • Java AWT
  • Java Swing
  • Java Enum
  • Java Annotations
  • Java main method
  • Java Interview Q

Copyright © 2012 – 2025 BeginnersBook . Privacy Policy . Sitemap