String Length and Substring

Part of: Using Objects

Calling Methods on Strings A String is an object, so it carries methods you invoke with dot notation : stringVariable.methodName(arguments). Two foundational methods are length() and substring(). length() length() returns the number of characters in the String as an int : Note the parentheses, length() is a method on String. (Arrays use .length with no parentheses; do not confuse them.) Indexing String characters are numbered starting at 0 . For "hello": - index 0 is 'h', index 1 is 'e', ... index 4 is 'o'. - The last valid index is always length() - 1. substring() substring extracts part of a String. It has two forms: The two-argument form is inclusive of the start, exclusive of the end . The number of characters returned is end - start. Off-by-One Care The exclusive end trips up many students. To grab characters at indices 3, 4, 5 you write substring(3, 6), the end index is one past the last character you want. Asking for an index outside 0..length() throws a StringIndexOutOfBoundsException. Strings Are Immutable These methods never change the original String. substring returns a new String; the source is untouched: Because Strings are immutable , you must capture the result in a

Challenge: First and Last Character