• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Help with Chapter 3 review questions 2 and 10 (Java OCA 8 Programmer I Study Guide, Sybex)

 
John Consorti
Greenhorn
Posts: 12
1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello,

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?

taken from question 2 page 153

taken from question 10 page 156

Thank you in advance,
John
 
Roel De Nijs
Sheriff
Posts: 10666
144
AngularJS Chrome Eclipse IDE Hibernate Java jQuery MySQL Database Spring Tomcat Server
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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).

Have you already read this excellent article about string literals and the String Literal Pool?

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:
  • new String("abc") - one object or two?
  • strings and the string pool
  • What is now right about the String?


  • Hope it helps!
    Kind regards,
    Roel

    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?
     
    John Consorti
    Greenhorn
    Posts: 12
    1
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    Thank you, that makes perfect sense I will need to refer to it from now on as the String constant pool to remind myself.  Thanks!
     
    • Post Reply
    • Bookmark Topic Watch Topic
    • New Topic