Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 3 of 3
  1. #1
    New to the CF scene
    Join Date
    Nov 2010
    Location
    Burlington, Vermont, USA
    Posts
    2
    Thanks
    1
    Thanked 0 Times in 0 Posts

    Question Comparing strings using ==

    I'm newish to Java- hoping someone can explain this to me...
    My understanding was that the equals method was necessary for comparing strings, because == compared the objects, not the literals. How come the code below returns true for c?
    If I declare a and b using String a= new String("hi") instead, then c is false.
    I thought that String a="hi" did the same thing as String a= new String("hi")?

    Any help would be most appreciated! Thanks.
    Code:
    public class TryEquals{
        public static void main(String [] args){
            String a="hi";
            String b="hi";
            boolean c=(a==b);
            System.out.println(c);
            }
    }

  • #2
    Supreme Master coder! Old Pedant's Avatar
    Join Date
    Feb 2009
    Posts
    25,189
    Thanks
    75
    Thanked 4,341 Times in 4,307 Posts
    Sting *LITERALS* are always allocated once, only, out of a static pool.

    So what you have *really* done here is equivalent this:
    Code:
        System.createStringLiteral("hi");
        a = System.getStringFromLiteralPool("hi");
        b = System.getStringFromLiteralPool("hi");
    so a and b are *really* referring to *EXACTLY* the same object. And so the == operator really is testing object equivalence!

    FWIW, you actually *can* force Java to see a pair of dynamically created strings as the same object, if they contain the same characters. You have to call the intern() method and then use the returned reference.

    Here, look at this:
    http://download.oracle.com/javase/1....g.html#intern()

    Essentially, *all* string literals are automatically returned via hidden calls to intern().
    An optimist sees the glass as half full.
    A pessimist sees the glass as half empty.
    A realist drinks it no matter how much there is.

  • Users who have thanked Old Pedant for this post:

    csmacf (11-15-2010)

  • #3
    New to the CF scene
    Join Date
    Nov 2010
    Location
    Burlington, Vermont, USA
    Posts
    2
    Thanks
    1
    Thanked 0 Times in 0 Posts
    Wow- that's really helpful. Thanks for taking the time. I had looked at the String reference you cited, but I doubt I would have ever found it.


  •  

    Tags for this Thread

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •