A String is an immutable reference type in java.lang. You can create one with a string literal or with new String(). Because Strings are immutable, methods like substring and toUpperCase return new String objects; they do not modify the original. String indices run from 0 to length() - 1. The five String methods on the Java Quick Reference are length(), substring(from, to), substring(from), indexOf(str), equals(other), and compareTo(other).
- String immutability: Once created, a String's characters cannot change. Methods return new String objects rather than modifying the original.
- length(): Returns the number of characters in the String as an int. "hello".length() returns 5.
- substring(from, to): Returns the substring from index from up to but not including index to. "hello".substring(1, 3) returns "el".
- indexOf(str): Returns the index of the first occurrence of str, or -1 if not found.
- equals(other): Returns true if the two Strings contain the same sequence of characters. Use equals, not ==, to compare String content.
- compareTo(other): Returns a negative int if this String comes before other lexicographically, 0 if equal, positive if after.
For String s = "computer"; what does s.substring(0, 4) return? What does s.indexOf("put") return? What does s.length() return?