Substring

To extract a piece of a string (either a single character or several characters in a row), use the substring command:

String s = "hello";

//has value "lo"
String sub = s.substring(3); 

Alternatively, we can specify the starting index (inclusive) and the ending index (non-inclusive):

String s = "hello";

//has value "el"
String sub1 = s.substring(1, 3); 

//has value "llo"
String sub2 = s.substring(2, 5); 

//has value "h"
String sub3 = s.substring(0, 1); 

Note that when we extract a single character with substring as we did with s.substring(0, 1) above, we get the result as the string “h” (which must be stored in a String variable). If we were to instead use s.charAt(0), we would get the result as the CHARACTER ‘h’ (which must be stored in a char variable).