The main tenet here is that strings are immutable in Java. That means that once created, they cannot be changed.
This allows a JVM to make optimisations. So a good JVM will optimise (87) to the creation of one object. But a poor one may not. There's nothing compelling a JVM to make such an optimisation. The JLS does not demand this.
So the sensible answer to (87) is probably 1, but no more than 3.
(89) is more difficult. In most cases you'll find one object being created in the global string pool and a second one (due to your using new
) being created in normal memory. However, I can see no reason why this couldn't be optimised to just one string with s
referring to the global string pool directly.
So the sensible answer to (89) is probably 2, but just might be 1.