This week's book giveaway is in the Reactive Progamming forum. We're giving away four copies of Reactive Streams in Java: Concurrency with RxJava, Reactor, and Akka Streams and have Adam Davis on-line! See this thread for details.
Could someone please explain to me how the string pool works? for example below why does #2 return "one" and "four" but #10 return only "equals"? does it matter the ordering of the string object and the "string" value?
John Consorti wrote:Could someone please explain to me how the string pool works? for example below why does #2 return "one" and "four" but #10 return only "equals"? does it matter the ordering of the string object and the "string" value?
It is not the "string pool", but the String Literal (or Constant) Pool. And this name already suggests why in the first example both if statements evaluate to true and in the second example only the if statement with the equals() method invocation. Only String literals are added to the String Literal Pool (hence its name) and in the second example the String referred by the reference variable a is not a literal (it is created at runtime).
In the OCAJP forum you'll find plenty of topics about strings and the String Literal Pool. If you want to read a bit more about this hard to understand topic, the following topics are definitely worth reading as they offer great explanations with informative code snippets:
PS. Always use code tags when posting code to the forums. Unformatted or unindented code is extremely hard to read and many people that might be able to help you will just move along to posts that are easier to read. Please click this link ⇒ UseCodeTags ⇐ for more information. Properly indented and formatted code greatly increases the probability that your question will get quicker, better answers. Jeanne already added the code tags for you. See how much easier the code is to read?