Results 1 to 19 of 19
Like Tree2Likes
  • 1 Post By gimbal2
  • 1 Post By suhaas_mohandos

Thread: String == and equals

  1. #1
    jmohandos304 is offline Member
    Join Date
    Apr 2014
    Posts
    90
    Rep Power
    0

    Default String == and equals

    Java Code:
    class Test
    {
         public static void main (String[] args) 
         {   
            String s1=new String("hi");
            String s2="hi";
            System.out.println("s1==s2:"+(s1==s2));
            System.out.println("s1.equals(s2):"+(s1.equals(s2)));
        }
    }
    Output:
    s1==s2:false
    s1.equals(s2):true

    How come s1==s2 is false when I have not used new operator to assign value to s2? Should it not be using the same value of "hi" which is already available?

  2. #2
    kneitzel is offline Senior Member
    Join Date
    Feb 2014
    Posts
    447
    Rep Power
    1

    Default Re: String == and equals

    Hi,
    == checks if the referenc is the same.
    Equals checks, if the content is the same

    So if we talk about houses:
    == would check the address.
    Equals simply checks, if the houses are equal. So there can be 2 houses at different locations that are equal.

    Just search on google and you will find more discussions about it.

  3. #3
    jmohandos304 is offline Member
    Join Date
    Apr 2014
    Posts
    90
    Rep Power
    0

    Default Re: String == and equals

    All that is ok. When there is an object with "hi" what is the need to create a new object when I am not using new keyword for s2? Can it not refer to the same object as s1?

  4. #4
    Tolls is offline Moderator
    Join Date
    Apr 2009
    Posts
    12,014
    Rep Power
    20

    Default Re: String == and equals

    If you didn't want s1 to refer to a new String then don't do "new String("hi")".
    That implies you don't want to use the "hi" that's been stored in the String pool.
    Please do not ask for code as refusal often offends.

    ** This space for rent **

  5. #5
    gimbal2 is offline Just a guy
    Join Date
    Jun 2013
    Location
    Netherlands
    Posts
    4,029
    Rep Power
    6

    Default Re: String == and equals

    Quote Originally Posted by jmohandos304 View Post
    Java Code:
            String s1=new String("hi");
    Envision what is happening on this line of code. What you are forcing Java to do.

    1) create String "hi" and put it in the String pool (that's the part of the code marked blue in the code you posted; a String literal)
    2) create your own unique String object (new String(...))
    3) take the character array of the existing "hi" String in the pool and stick it in your own unique String object

    And that's how you end up with two different String objects with the same value.
    jmohandos304 likes this.
    "Syntactic sugar causes cancer of the semicolon." -- Alan Perlis

  6. #6
    jmohandos304 is offline Member
    Join Date
    Apr 2014
    Posts
    90
    Rep Power
    0

    Default Re: String == and equals

    I am talking about s2, not s1. My question is very simple. I have not explicitly mentioned s2 using new. So why can't s2 take the value already in string pool?

  7. #7
    jmohandos304 is offline Member
    Join Date
    Apr 2014
    Posts
    90
    Rep Power
    0

    Default Re: String == and equals

    Gimbal2's answer seems to be satisfactory.

  8. #8
    gimbal2 is offline Just a guy
    Join Date
    Jun 2013
    Location
    Netherlands
    Posts
    4,029
    Rep Power
    6

    Default Re: String == and equals

    It IS taking that value.
    "Syntactic sugar causes cancer of the semicolon." -- Alan Perlis

  9. #9
    jmohandos304 is offline Member
    Join Date
    Apr 2014
    Posts
    90
    Rep Power
    0

    Default Re: String == and equals

    Agreed Sir. Your answer seems to be convincing.

  10. #10
    jmohandos304 is offline Member
    Join Date
    Apr 2014
    Posts
    90
    Rep Power
    0

    Default Re: String == and equals

    3) take the character array of the existing "hi" String in the pool and stick it in your own unique String object

    This line is regarding s1 or s2?

  11. #11
    R03
    R03 is offline Member
    Join Date
    Apr 2014
    Posts
    10
    Rep Power
    0

    Default Re: String == and equals

    Sorry jmohandos304

    I don't mean to hijack your thread.. but your thread very useful for me.. because i'm still learn java..

    when i try your code like below :
    Java Code:
    class Equal {
    	public static void main (String[] args){
    		String s1 = new String ("Hi");
    		String s2 = new String ("Hi");
    		
    		System.out.println ("s1==s2: " + (s1==s2)); //if i change to "!=" result going true..
    		System.out.println ("s1.equals(s2): " + (s1.equals(s2)));
    		
    		
    	}
    
    }
    i got same result :

    s1==s2: false
    s1.equals(s2): true

    -------------------------------------------------------------------------------------------------

    i've search to know what differently both..
    "==" compare in memory location --> which mean --> the new object s1 & s2 on the same memory location ? how to know the object on the same memory location ? there is a way to know it ?
    "equals" compare the value of object --> which mean --> 'Hi .. value' are the same value of object s1 & s2 ?


    Thank you

    Regards,
    R03.

  12. #12
    Join Date
    Aug 2013
    Posts
    55
    Rep Power
    0

    Default Re: String == and equals

    mbschultz97 likes this.

  13. #13
    kneitzel is offline Senior Member
    Join Date
    Feb 2014
    Posts
    447
    Rep Power
    1

    Default Re: String == and equals

    My understanding of all this is quite easy:
    - There is a list of "intern" strings. And of course: Java tries to use this when possible which simply leads to confusion, because suddenly "s1==s2" seems to "work".
    - What is happening in a line 'String s1 = new Sting("hi");'?
    a) The string "hi" is required. The compiler made sure that it is inside the internal string table at startup.
    b) a new string is created which is not using the intern version of "hi" - It is using a copy of it. ("Initializes a newly created String object so that it represents the same sequence of characters as the argument; in other words, the newly created string is a copy of the argument string" (*1) )
    - So when you have 'String s2 = "hi";' the same string is used as in the line before (just the "hi" part!).
    Maybe it helps to extend your example to
    String s0 = "hi";
    String s1 = new String(s0);
    String s2 = "hi";
    You just wrote the 2 first lines in one line if you want to see it that way.

    (*1) Copied from the description of the constructor at String (Java Platform SE 7 )

    With kind regards,

    Konrad

  14. #14
    jim829 is offline Senior Member
    Join Date
    Jan 2013
    Location
    Northern Virginia, United States
    Posts
    3,616
    Rep Power
    5

    Default Re: String == and equals

    Quote Originally Posted by jmohandos304 View Post
    I am talking about s2, not s1. My question is very simple. I have not explicitly mentioned s2 using new. So why can't s2 take the value already in string pool?
    Here is the proof.

    Java Code:
    public class StringReferenceDemo {
    
       public static void main(String[] args) {
          String s1 = new String("hi"); // creates String pool entry
                                        // and a reference to a new object
          System.out.println(s1 == s1.intern()); // false - different references, different objects
          String s2 = "hi"; // use object from String pool
          System.out.println(s2 == s2.intern());  // true - same as string pool object
          System.out.println(s2 == s1.intern()); // true - using string pool
                                                 // objects
       }
    
    }
    Regards,
    Jim
    Last edited by jim829; 05-13-2014 at 04:00 PM.
    The Java™ Tutorial | SSCCE | Java Naming Conventions
    Poor planning our your part does not constitute an emergency on my part.

  15. #15
    Join Date
    Aug 2013
    Posts
    55
    Rep Power
    0

    Default Re: String == and equals

    Now that I have understood it, a small twist to the question. Are Code 1 and Code 2 effectively the same?

    Code 1:
    Java Code:
    class Test
    {
         public static void main (String[] args)
         {  
            String s1=new String("hi");
            String s2="hi";
          }
    }
    Code 2:
    Java Code:
    class Test
    {
         public static void main (String[] args)
         {  
            String s1="hi";
            String s2="hi";
          }
    }

  16. #16
    kneitzel is offline Senior Member
    Join Date
    Feb 2014
    Posts
    447
    Rep Power
    1

    Default Re: String == and equals

    No they are not the same, because in your first code, s1 != s2 but in the second code s1 == s2. So they are not the same.

    But if you always compare strings with an equals call and do not care about the memory consumed, then the code could be exchanged. (In fact I would never user String s1 = new String("hi"); if I do not have a good reason to do exactly that!)

    Konrad

  17. #17
    Join Date
    Aug 2013
    Posts
    55
    Rep Power
    0

    Default Re: String == and equals

    That helped.

  18. #18
    JosAH's Avatar
    JosAH is online now Moderator
    Join Date
    Sep 2008
    Location
    Voorschoten, the Netherlands
    Posts
    13,526
    Blog Entries
    7
    Rep Power
    20

    Default Re: String == and equals

    This question only rises again and again because all those people asking it are spoiled, no ruined for life, by their exposure to some form of Basic that pretends that a String is some form of primitive, atomic type (such as a byte). They never ask the same question w.r.t. a, say, Person class or whatever. SmallTalk does a better job than Java does: it doesn't even have primitive types (e.g. ints have methods too). I hope that Java 9 is not going to have user defined overloaded methods ...

    kind regards,

    Jos
    cenosillicaphobia: the fear for an empty beer glass

  19. #19
    gimbal2 is offline Just a guy
    Join Date
    Jun 2013
    Location
    Netherlands
    Posts
    4,029
    Rep Power
    6

    Default Re: String == and equals

    Quote Originally Posted by JosAH View Post
    This question only rises again and again because all those people asking it are spoiled, no ruined for life, by their exposure to some form of Basic that pretends that a String is some form of primitive
    Nowadays I'd blame Javascript or PHP ;)
    "Syntactic sugar causes cancer of the semicolon." -- Alan Perlis

Similar Threads

  1. Equals
    By java4amanda in forum New To Java
    Replies: 4
    Last Post: 06-11-2012, 08:12 AM
  2. using .equals
    By droidus in forum New To Java
    Replies: 11
    Last Post: 01-21-2012, 03:33 AM
  3. c always equals a*b
    By imorio in forum New To Java
    Replies: 3
    Last Post: 11-12-2010, 02:32 PM
  4. == and equals()
    By arefeh in forum New To Java
    Replies: 13
    Last Post: 01-05-2010, 04:56 PM
  5. Replies: 0
    Last Post: 01-25-2008, 11:13 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
  •