Phase IX
Text and Types
The type you use most, and the trick that lets one class work with any type.
Strings are the most used type in Java, and they behave unlike anything else. Two design choices explain all of it, and they finally answer the == question left open in Phase III. Then generics: how one class can hold any type safely, what the compiler actually does to make that work, and why the answer explains several error messages that otherwise look arbitrary.
When you finish this phase you can
- State the one rule that decides whether a String goes in the pool or on the heap
- Explain why String had to be immutable before the pool could exist
- Measure the cost of joining text with + and fix it with StringBuilder
- Write a generic class and a generic method, and bound a type parameter
- Explain type erasure, and what it stops you from doing
- 9.1Strings: The Pool and ImmutabilityA String is a character array with a wrapper around it. Two design choices make it behave unlike anything else in Java, and they finally explain the == answer that surprised you in Phase III.The String Pool
- 9.2String Methods and StringBuilderFifty methods you do not need to memorise, and one class you do. Joining text in a loop is the commonest slow thing in beginner Java, and the fix is one line.StringBuilder
- 9.3GenericsOne class that works with any type, without giving up type checking. Before generics you used Object and a cast, and the cast failed while the program was running.GenericsType erasure
- 9.4Wildcards: `extends` and `super`A Dog is an Animal, but a List of Dogs is not a List of Animals. That refusal protects you, and wildcards are how you work around it without losing the protection.WildcardsPECS