Substring in Java

A part of string is called substring. In other words, substring is a subset of another string. In case of substring startIndex is inclusive and endIndex is exclusive.

Note
Index starts from 0.

You can get substring from the given string object by one of the two methods:

  1. public String substring(int startIndex): This method returns new String object containing the substring of the given string from specified startIndex (inclusive).
  2. public String substring(int startIndex, int endIndex): This method returns new String object containing the substring of the given string from specified startIndex to endIndex.

In case of string:

  • startIndex: inclusive
  • endIndex: exclusive

Let's understand the startIndex and endIndex by the code given below.

Example #1
snippet
String s="hello";
   System.out.println(s.substring(0,2));//he

In the above substring, 0 points to h but 2 points to e (because end index is exclusive).

Example #2
snippet
public class TestSubstring{
 public static void main(String args[]){
   String s="SachinTendulkar";
   System.out.println(s.substring(6));//Tendulkar
   System.out.println(s.substring(0,6));//Sachin
 }
}
Output
Tendulkar Sachin
Related Tutorial
Follow Us
https://www.facebook.com/Rookie-Nerd-638990322793530 https://twitter.com/RookieNerdTutor https://plus.google.com/b/117136517396468545840 #
Contents +