1 2 Previous Next 16 Replies Latest reply: Dec 12, 2009 12:24 AM by 843789 RSS

    Clarification request for == on Strings

    843789
      I've tested the following code, and it prints true.
      String s1 = "dog";
      String s2 = "dog";
      System.out.println(s1 == s2);
      But the following code prints false.
      String s1 = new String("dog");
      String s2 = new String("dog");
      System.out.println(s1 == s2);
      And I don't really understand why. I was under the impression that the latter two snippets were the same, leaving the second code snippet redundant, unless a copy of a String needed to be obtained. Could someone please explain to me why the two println statements result in different outputs?

      Thanks,
      sca.tj
        • 1. Re: Clarification request for == on Strings
          843789
          This is Java 101. You need to start here: [http://java.sun.com/docs/books/tutorial/java/index.html]

          == compares two references to see if they point to the exact same object. Since the new operator by definition creates a new Object, s1 and s2 necessarily must point to different objects. So == must return false.

          That's why you shouldn't use the new operator to create Strings unless you have good reason.

          In the first snippet, because the string "dog" is interned into the class definition, the two references point to the same object.
          • 2. Re: Clarification request for == on Strings
            794081
            I think [cottonm's reply|http://forums.sun.com/thread.jspa?messageID=10884634#10884634] can be applied to this thread as well.
            • 3. Re: Clarification request for == on Strings
              843789
              sca.tj wrote:
              String s1 = "dog";
              String s2 = new String("dog");
              I was under the impression that the latter two snippets were the same, leaving the second code snippet redundant, unless a copy of a String needed to be obtained.
              I don't know what you mean by "latter two snippets"... I only see two snippets total... but those two statements are not the same.
              • 4. Re: Clarification request for == on Strings
                843789
                In the first snippet, s1 is a new string, and so a new String object is created. s2 is created as a reference to the string object "abc".

                in snip 2, you explicitly declare two new Objects. Because the == operator compares references rather than eqality of the strings content,
                in snippet 1:

                s1 is a reference to "abc", and so is s2; == returns true;

                in snippet 1:

                s1 is a reference to a new String ("abc"), and so is s2; == returns false because they reference two different objects.

                edit: like I didnt know that was going to happen :)

                Edited by: anotherAikman on Dec 11, 2009 12:03 PM

                Edited by: anotherAikman on Dec 11, 2009 12:04 PM
                • 5. Re: Clarification request for == on Strings
                  843789
                  Ignoring the fact that "abc" wasn't mentioned at all, you're close but not quite on.
                  In the first snippet, s1 is a new string, and so a new String object is created. s2 is created as a reference to the string object "abc".
                  s1 isn't assigned a new String per se. As I understand it, Strings which appear as literals in a Class are added to the String constant pool (see String.intern) when the Class is first initialized (or loaded, not sure which; but either way before the Class can be used). By doing this:
                  String s1 = "dog";
                  you're just assigning the instance of String that already exists in the constant pool to a reference variable s1. There is no way to say "which line" created the String because the String object predates all of those assignments.

                  You might be interested in running this:
                  public class StringInternTest {
                     public static void main(String[] args) {
                        System.out.println(new String("abc") == new String("abc"));
                        
                        System.out.println("abc" == "abc");
                        System.out.println(new String("abc").intern() == "abc");
                        System.out.println(new String(new char[]{'a', 'b', 'c'}).intern() == "abc");
                        System.out.println("abc" == StringInternTestClass.STR);
                     }
                  }
                  
                  class StringInternTestClass {
                     public static String STR = "abc";
                  }
                  • 6. Re: Clarification request for == on Strings
                    3004
                    endasil wrote:
                    Ignoring the fact that "abc" wasn't mentioned at all, you're close but not quite on.
                    In the first snippet, s1 is a new string, and so a new String object is created. s2 is created as a reference to the string object "abc".
                    s1 isn't assigned a new String per se. As I understand it, Strings which appear as literals in a Class are added to the String constant pool (see String.intern) when the Class is first initialized (or loaded, not sure which; but either way before the Class can be used).
                    It's when the class is initialized. While initialization is technically a separate step from loading, we can consider them a single step for the purposes of this discussion, lumped together under the heading, "all the stuff that happens the first time a class is mentioned, to prepare the class for use, before the code that uses it actually executes."
                    By doing this:
                    String s1 = "dog";
                    you're just assigning the instance of String that already exists in the constant pool to a reference variable s1. There is no way to say "which line" created the String because the String object predates all of those assignments.
                    Correct. Executing that line does not create any String objects. Loading that class created a String object in the constant pool.
                    • 7. Re: Clarification request for == on Strings
                      796447
                      michael_schmid wrote:
                      I think [cottonm's reply|http://forums.sun.com/thread.jspa?messageID=10884634#10884634] can be applied to this thread as well.
                      Agreed! There are an unlimited number of awards to give customers like this one, so even though the other guy won his all expense trip, this guy can have one too.
                      • 8. Re: Clarification request for == on Strings
                        843789
                        I was under the impression that this might have been a "Java 101" question, like you said, based on the simplicity of the code, but I wasn't too sure. However, out of the programming classes that I have taken, this specification was never made clear to me, and only recently stemmed from an AP multiple-choice question in the "Java software solutions for AP* Computer Science A" book by John Lewis, Wiliam Loftus, and Cara Cocking, in which the book's answer was proved wrong, and then thrown into question when someone else actually wrote it using the new operator. That information aside, I would like to know where exactly it explains the interning of Strings in the link that you've provided, endasil, as I searched, and did not find it.

                        I know of a few friends that would like to take part in this community, and ask questions more frequently, as it is a great resource full of intelligent people, but quite a few of them don't do that as much as they would like to. Mostly because of rude remarks like the one above. It can be discouraging.

                        Thanks, I guess.
                        sca.tj
                        • 9. Re: Clarification request for == on Strings
                          3004
                          sca.tj wrote:
                          I would like to know where exactly it explains the interning of Strings
                          [http://java.sun.com/docs/books/jls/third_edition/html/lexical.html#3.10.5]
                          [http://java.sun.com/docs/books/jls/third_edition/html/lexical.html#19369]
                          [http://java.sun.com/docs/books/jvms/second_edition/html/Concepts.doc.html#29971]
                          [http://java.sun.com/docs/books/jvms/second_edition/html/ConstantPool.doc.html#80050]
                          • 10. Re: Clarification request for == on Strings
                            3004
                            sca.tj wrote:
                            I know of a few friends that would like to take part in this community, and ask questions more frequently, as it is a great resource full of intelligent people, but quite a few of them don't do that as much as they would like to. Mostly because of rude remarks like the one above. It can be discouraging.
                            You mean comments that point out the fact that the question has been asked many times before and suggest that the person do some research before posting?
                            • 11. Re: Clarification request for == on Strings
                              843789
                              Thanks for that, although I'd also like to know where specifically in the source that endasil posted, as he said I should "start here: http://java.sun.com/docs/books/tutorial/java/index.html."

                              And no, I meant exactly what I said: "rude remarks."
                              I also did not happen to find any threads that answered what was looking for. Perhaps I didn't search well enough, though.
                              • 12. Re: Clarification request for == on Strings
                                3004
                                sca.tj wrote:
                                Thanks for that, although I'd also like to know where specifically in the source that endasil posted, as he said I should "start here: http://java.sun.com/docs/books/tutorial/java/index.html."
                                I'd think you'd be able to find that on your own.
                                • 13. Re: Clarification request for == on Strings
                                  843789
                                  I apologize, I didn't mean for that to seem like I was asking for you to show me where it is. I browse there often, but maybe not often enough, but I was merely trying to get to endasil's point in directing me to that link, but I suppose I'm reading too much into it. I'll be sure to look there.

                                  Thanks for your time.
                                  • 14. Re: Clarification request for == on Strings
                                    3004
                                    No biggie. I'm not sure how much detail that link provides about the string pool. Keep in mind, though, that whatever you do find there is presented to explain concepts to a beginner, and may gloss over some stuff. The JLS and VM spec I linked to are the authoritative docs for the language and the runtime, respectively.
                                    1 2 Previous Next