Results 1 to 4 of 4
  1. #1
    AndrewM16921 is offline Senior Member
    Join Date
    Jan 2009
    Location
    CA, USA
    Posts
    264
    Rep Power
    6

    Default String == String

    This is weird.

    So, I was teaching somebody how to use Java and I had essentially said if you compare two strings with == they are not necessarily equal even if they have the same value. So...

    String str1 = "text";
    String str2 = "text";

    System.out.println(str1 == str2);

    This printed out true.

    ...WHAT? Does == now evaluate based on .equals rather than the reference or something? Or am I missing something here...

  2. #2
    2by4 is offline Banned
    Join Date
    Dec 2011
    Posts
    143
    Rep Power
    0

    Default Re: String == String

    The compiler knows that a constant cannot change. So it creates only on copy of "text" in memory.

    Try this..

    String str1 = "text";
    String str2 = new String("text");

    This also..

    String str1 = "text";
    String str2 = str1 + "";

    System.out.println(str1 == str2);

    I guess it all depends on how clever the compiler is.
    Last edited by 2by4; 12-18-2011 at 12:59 AM.

  3. #3
    pbrockway2 is offline Moderator
    Join Date
    Feb 2009
    Location
    New Zealand
    Posts
    4,585
    Rep Power
    12

    Default Re: String == String

    if you compare two strings with == they are not necessarily equal even if they have the same value
    That's right, if you mean by "have the same value" that they are made up of the same characters in the same order.

    Your example is not inconsistent with that. Two strings made up of ... (equals() for short) may or may not be ==. If you want an example that prints false, try

    Java Code:
    String str1 = new String("text");
    String str2 = new String("text");
    In the example you tried the strings were interned.

  4. #4
    AndrewM16921 is offline Senior Member
    Join Date
    Jan 2009
    Location
    CA, USA
    Posts
    264
    Rep Power
    6

    Default Re: String == String

    Ah, I get it. I don't like it, but I get it. =P

    Thanks.

Similar Threads

  1. Replies: 11
    Last Post: 08-15-2011, 11:12 AM
  2. Replies: 12
    Last Post: 11-26-2010, 09:33 AM
  3. Replies: 1
    Last Post: 11-04-2010, 07:53 PM
  4. Replies: 7
    Last Post: 11-03-2009, 03:18 AM
  5. Replies: 0
    Last Post: 11-20-2007, 05:59 PM

Posting Permissions

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