String Methods can be used to Manipulate Strings.
- Java subString method returns the substring of this String.
- This method always returns a new string, and the original String remains unchanged because String is immutable in Java.
- It’s a commonly used method in Java.
You have a string & you don’t need to use the whole string
.substring()
method can be used to get a part of the string
subString(startIndex,endIndex)
- startIndex – beginning one is inclusive. means Includes that character
- endIndex – end one is exclusive; it does not involve the character
- The string is an object of the String class
String str="ABCDEFG"; System.out.println(str.substring(0,4)); //returns ABCD
- Above, we use subString starts from 0 ends with 4.
- Starts from 0 is A to, but 4 is E
- Index always starts from 0
Java subString()
public class Main { public static void main(String args[]){ // Initializing the String String str = "ABCDEFGHIJK"; // Applying substring() to extract substring System.out.println(str.subString(0)); // returns ABCDEFGHIJK } }
public class Main { public static void main(String args[]){ String str = "ABCDEFGHIJK"; System.out.println(str.subString(1,5)); // returns BCDE } }