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
- public class SubstringExample1{
- public static void main(String args[]){
- String str="javainsimpleway";
- System.out.println(str.substring(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
- public class SubstringExample2{
- public static void main(String args[]){
- String str="javainsimpleway";
- System.out.println(str.substring(6,13));
- }
- }
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)
typo error on this page :–
public class SubstringExample2{
public static void main(String args[]){
String str=”javainsimpleway”;
System.out.println(str.substring(6,13));
}
}
Output
simple
Output must be simplew instead of simple
Updated it.
Thanks for pointing out !!