Substring()


Let us understand Substring() method


This method returns a new string which is a part of the given string.

It begins with a character at the specified index and extends to either end of string or specified end index.


There are 2 overloaded methods of substring


public String substring(int startIndex)

public String substring(int startIndex, int endIndex)


public String substring(int startIndex)


This method returns part of the string starting from specified index till end of the string

Example

  1. public class SubstringExample1{  
  2. public static void main(String args[]){  
  3. String str="javainsimpleway";  
  4. System.out.println(str.substring(6));
  5.  }
  6. }
public class SubstringExample1{  
public static void main(String args[]){  
String str="javainsimpleway";  
System.out.println(str.substring(6));
 }
}



We can see that the substring returned, has characters from specified starting point to the end of original string.

public String substring(int startIndex, int endIndex)


This method returns part of the string starting from start index till end index

Note :

Startindex is inclusive and endIndex is exclusive.


Example

  1. public class SubstringExample2{  
  2. public static void main(String args[]){  
  3. String str="javainsimpleway";  
  4. System.out.println(str.substring(6,13));
  5.  }
  6. }
public class SubstringExample2{  
public static void main(String args[]){  
String str="javainsimpleway";  
System.out.println(str.substring(6,13));
 }
}




We can see that the substring returned, has characters from specified starting point to the specified end point(end index is exclusive)

About the Author

Founder of javainsimpleway.com
I love Java and open source technologies and very much passionate about software development.
I like to share my knowledge with others especially on technology 🙂
I have given all the examples as simple as possible to understand for the beginners.
All the code posted on my blog is developed,compiled and tested in my development environment.
If you find any mistakes or bugs, Please drop an email to kb.knowledge.sharing@gmail.com

Connect with me on Facebook for more updates

Share this article on