This activity helps students remember how to use substring() properly and avoid common mistake of not including the last letter or not going far enough into the string to create the substring they intended.
This activity sets up markers (fence posts) that make the numbers you need to use in substring()to get the characters you intend clear.
Java’s substring method doesn’t retrieve the characters in the string using their index location which can confuse students.
Students want to take the string “Serita” and place fence posts between all the characters.
String name = “Serita”; will look like |S|E|R|I|T|A|
Have each student write down the string “Serita” with fence posts between each letter.
Next, number fence posts starting with 0.
0 1 2 3 4 5 6
Now all the letters are between fence posts. Tell students that calls to substring() use the fence post numbers to determine which letters to use in the substring.
Ask students what the following calls to substring() will return.
name.substring(0,3) ⇒ ser
name.substring(4,name.length()) ⇒ ta
Watch out: Be sure students don’t mistakenly use this method with charAt(), which retrieves the character at it’s index (not between fence posts).