Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 17 of 17

Thread: Comparison of Objects and such

  1. #1
    Member
    Join Date
    Sep 2013
    Posts
    64
    Thanks
    24
    Thanked 0 Times in 0 Posts

    Default Comparison of Objects and such

    Let's say I have two strings:
    String1 = "hi";
    String2 = "hi";

    Is String1 == String2 true?
    Is String1.equals(String2) true?

    What exactly is the difference between these two statements? When do those differences come up?

    From what I saw online, it has to do with a reference...or something....but I find it confusing.

    Can someone explain it in a way that's easy to understand?


  2. #2
    Super Moderator
    Join Date
    Jun 2013
    Location
    So. Maryland, USA
    Posts
    5,517
    My Mood
    Mellow
    Thanks
    215
    Thanked 698 Times in 680 Posts

    Default Re: Comparison of Objects and such

    I think you should answer the questions about whether "==" and equals() provide the same results. Write a simple little program and see what happens. You should also search the Internet for an explanation of "string pooling" in Java.

  3. #3
    Junior Member
    Join Date
    Oct 2013
    Posts
    11
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Comparison of Objects and such

    String1 and String2 both are reffering same data in String pool.

    So String1 == String2 will be TRUE (As both variables referring same data)

    And String1.equals(String2) will be TRUE (As both variables have same contents)

  4. #4
    Forum VIP
    Join Date
    Jul 2010
    Posts
    1,676
    Thanks
    25
    Thanked 329 Times in 305 Posts

    Default Re: Comparison of Objects and such

    Going off of GregBrannon's comment: consider that String is an object, not a primitive (like an int, for example).

    --- Update ---

    Quote Originally Posted by hs82 View Post
    String1 and String2 both are reffering same data in String pool.

    So String1 == String2 will be TRUE (As both variables referring same data)

    And String1.equals(String2) will be TRUE (As both variables have same contents)
    Wrong. String1 == String2 is FALSE
    NOTE TO NEW PEOPLE LOOKING FOR HELP ON FORUM:

    When asking for help, please follow these guidelines to receive better and more prompt help:
    1. Put your code in Java Tags. To do this, put [highlight=java] before your code and [/highlight] after your code.
    2. Give full details of errors and provide us with as much information about the situation as possible.
    3. Give us an example of what the output should look like when done correctly.

    Join the Airline Management Simulation Game to manage your own airline against other users in a virtual recreation of the United States Airline Industry. For more details, visit: http://airlinegame.orgfree.com/

  5. #5
    Junior Member
    Join Date
    Oct 2013
    Posts
    11
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Comparison of Objects and such

    Please run following code and decide :

    public class StringMatch {

    public static void main(String[] args) {
    String s1 = "TRUE";
    String s2 = "TRUE";
    if(s1 == s2){
    System.out.println("MATCHED");
    }else{
    System.out.println("NOT MATCHED");
    }
    if(s1.equals(s2)){
    System.out.println("MATCHED");
    }else{
    System.out.println("NOT MATCHED");
    }
    }
    }

  6. #6
    Forum VIP
    Join Date
    Jul 2010
    Posts
    1,676
    Thanks
    25
    Thanked 329 Times in 305 Posts

    Default Re: Comparison of Objects and such

    hs82, are you asking me to run that code or the OP?
    NOTE TO NEW PEOPLE LOOKING FOR HELP ON FORUM:

    When asking for help, please follow these guidelines to receive better and more prompt help:
    1. Put your code in Java Tags. To do this, put [highlight=java] before your code and [/highlight] after your code.
    2. Give full details of errors and provide us with as much information about the situation as possible.
    3. Give us an example of what the output should look like when done correctly.

    Join the Airline Management Simulation Game to manage your own airline against other users in a virtual recreation of the United States Airline Industry. For more details, visit: http://airlinegame.orgfree.com/

  7. #7
    Junior Member
    Join Date
    Oct 2013
    Posts
    11
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Comparison of Objects and such

    Yes.. Because I have tested this using above code.

  8. #8
    Forum VIP
    Join Date
    Jul 2010
    Posts
    1,676
    Thanks
    25
    Thanked 329 Times in 305 Posts

    Default Re: Comparison of Objects and such

    Quote Originally Posted by hs82 View Post
    Yes.. Because I have tested this using above code.
    Oh, that's an interesting compiler trick. Apparently the compiler combines literal Strings in an optimization attempt.
    Now try these two examples which, while in spirit are the same, break the compiler's optimization trick:
    public class StringMatch {
     
    public static void main(String[] args) {
    String s1 = "TEST";
    String s2 = "TE";
    s2 = s2+"ST";
    if(s1 == s2){
    System.out.println("MATCHED");
    }else{
    System.out.println("NOT MATCHED");
    }
    if(s1.equals(s2)){
    System.out.println("MATCHED");
    }else{
    System.out.println("NOT MATCHED");
    }
    }
    }

    public class StringMatch {
     
    public static void main(String[] args) {
    String s1 = new String("TEST");
    String s2 = new String("TEST");
    if(s1 == s2){
    System.out.println("MATCHED");
    }else{
    System.out.println("NOT MATCHED");
    }
    if(s1.equals(s2)){
    System.out.println("MATCHED");
    }else{
    System.out.println("NOT MATCHED");
    }
    }
    }

    == should never be used to compare values of two Strings. String is an object, so == compares reference. Just because the compiler does a little trick to combine literals into the same reference does not mean it is a safe way to compare Strings.
    NOTE TO NEW PEOPLE LOOKING FOR HELP ON FORUM:

    When asking for help, please follow these guidelines to receive better and more prompt help:
    1. Put your code in Java Tags. To do this, put [highlight=java] before your code and [/highlight] after your code.
    2. Give full details of errors and provide us with as much information about the situation as possible.
    3. Give us an example of what the output should look like when done correctly.

    Join the Airline Management Simulation Game to manage your own airline against other users in a virtual recreation of the United States Airline Industry. For more details, visit: http://airlinegame.orgfree.com/

  9. #9
    Junior Member
    Join Date
    Oct 2013
    Posts
    11
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Comparison of Objects and such

    I agree that we shall never use == operator to compare two objects.

    Can you please explain little more about what you said about Compiler optimization in case of my code. Also will the String pool is going to have two separate string in following case:

    String s1 = new String("TEST");
    String s2 = new String("TEST");

    Thanks for sharing your views.

  10. #10
    Forum VIP
    Join Date
    Jul 2010
    Posts
    1,676
    Thanks
    25
    Thanked 329 Times in 305 Posts

    Default Re: Comparison of Objects and such

    Quote Originally Posted by hs82 View Post
    I agree that we shall never use == operator to compare two objects.

    Can you please explain little more about what you said about Compiler optimization in case of my code. Also will the String pool is going to have two separate string in following case:

    String s1 = new String("TEST");
    String s2 = new String("TEST");

    Thanks for sharing your views.
    The difference between:
    String s1 = new String("TEST");
    String s2 = new String("TEST");

    and:
    String s1 = "TEST";
    String s2 = "TEST";

    is that the second one initializes with a literal String, whereas the first one uses the String constructor. When the compiler optimizes, it combines the literal Strings with all the same value into a single reference. It does this to free up, what it sees as, unnecessarily allocated memory. When you initialize the String with the constructor, the compiler does not optimize it, since it is treating it like an Object, instead of a literal String.
    At first this would seem like really dangerous optimization because: what if you changed one of the values? Everything you know about changing the values in references would suggest the other String would also change. But this is not the case, since Strings are immutable, meaning their value cannot change. When you reinitialize a String, it does not change the value in the reference that the String was pointing to, it creates a whole new reference and reassigns the String's pointer to the new reference (without changing all the other Strings which reference the old value).
    When you create part of the String and then concatenate the rest (like in my first example code a few posts ago). The compiler does not process the concatenation, so it does not recognize the Strings have the same value, despite being initialized with literal Strings.
    Using the == to compare literal Strings is relying entirely on compiler optimization and not on the language constraints. There is no guarantee that part of the compiler optimization will exist in future compiler versions, or that it is compatible with previous compiler versions. When coding, you want to stay within the constraints of the language, not within whatever the current compiler will allow you to get away with.
    NOTE TO NEW PEOPLE LOOKING FOR HELP ON FORUM:

    When asking for help, please follow these guidelines to receive better and more prompt help:
    1. Put your code in Java Tags. To do this, put [highlight=java] before your code and [/highlight] after your code.
    2. Give full details of errors and provide us with as much information about the situation as possible.
    3. Give us an example of what the output should look like when done correctly.

    Join the Airline Management Simulation Game to manage your own airline against other users in a virtual recreation of the United States Airline Industry. For more details, visit: http://airlinegame.orgfree.com/

  11. #11
    Grand Poobah
    Join Date
    Mar 2011
    Posts
    1,545
    My Mood
    Grumpy
    Thanks
    0
    Thanked 167 Times in 158 Posts

    Default Re: Comparison of Objects and such

    Quote Originally Posted by aussiemcgr View Post
    Apparently the compiler combines literal Strings in an optimization attempt.
    Nothing to do with optimisation and everything to do with the String Literal Pool.
    Improving the world one idiot at a time!

  12. #12
    Junior Member
    Join Date
    Oct 2013
    Posts
    11
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Comparison of Objects and such

    Thanks you so much, for such a clear and logical explanation.

    String s1 = new String("TEST");
    String s2 = new String("TEST");

    In this case two Objects are created, with pointing to same string in String pool (Please correct me if I am misinterpreting your above answer)

    So if I do :

    s1 = new String("NEW");

    Then , in String pool, a new literal will be created "NEW".

    Also, what should be the ideal way to use Strings. Initializing with literal or using new String(" ") if we consider:
    1) Performance / optimization
    2) Security

    Thanks in advance.

  13. #13
    Forum VIP
    Join Date
    Jul 2010
    Posts
    1,676
    Thanks
    25
    Thanked 329 Times in 305 Posts

    Default Re: Comparison of Objects and such

    Quote Originally Posted by hs82 View Post
    Thanks you so much, for such a clear and logical explanation.

    String s1 = new String("TEST");
    String s2 = new String("TEST");

    In this case two Objects are created, with pointing to same string in String pool (Please correct me if I am misinterpreting your above answer)

    So if I do :

    s1 = new String("NEW");

    Then , in String pool, a new literal will be created "NEW".

    Also, what should be the ideal way to use Strings. Initializing with literal or using new String(" ") if we consider:
    1) Performance / optimization
    2) Security

    Thanks in advance.
    If you do a == on s1 and s2, you will get FALSE. They are not the same object.
    Literals are usually used to initialize Strings, but it is more of a convention than a requirement. As I said earlier, since Strings are immutable, there is not the concern of altering the values for other Strings when changing the value of one.
    NOTE TO NEW PEOPLE LOOKING FOR HELP ON FORUM:

    When asking for help, please follow these guidelines to receive better and more prompt help:
    1. Put your code in Java Tags. To do this, put [highlight=java] before your code and [/highlight] after your code.
    2. Give full details of errors and provide us with as much information about the situation as possible.
    3. Give us an example of what the output should look like when done correctly.

    Join the Airline Management Simulation Game to manage your own airline against other users in a virtual recreation of the United States Airline Industry. For more details, visit: http://airlinegame.orgfree.com/

  14. #14
    Junior Member
    Join Date
    Oct 2013
    Posts
    11
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Comparison of Objects and such

    I agree that == should never be used for comparing two objects.

    For this particular case or in any case == should never be used.

    But I want to know what is the best way to create String variables in general:
    1) Using String str = "ABC";
    or
    2) Using String str = new String("ABC");

    As per concept of String pooling, we should use first method. What is your opinion on this.

  15. #15
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,139
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: Comparison of Objects and such

    what is the best way
    If you are talking about having the compiler generate the fewest lines of code, write a small program with the different techniques, compile it and use the javap command to write out the generated code so you can see what is generated.
    If you don't understand my answer, don't ignore it, ask a question.

  16. #16
    Forum VIP
    Join Date
    Jul 2010
    Posts
    1,676
    Thanks
    25
    Thanked 329 Times in 305 Posts

    Default Re: Comparison of Objects and such

    Quote Originally Posted by hs82 View Post
    I agree that == should never be used for comparing two objects.

    For this particular case or in any case == should never be used.

    But I want to know what is the best way to create String variables in general:
    1) Using String str = "ABC";
    or
    2) Using String str = new String("ABC");

    As per concept of String pooling, we should use first method. What is your opinion on this.
    == does have a use: when you want to see if two objects are the same physical reference. For example, the java.util.EventObject class is used in GUIs for event handling. This object has a getSource() method, which returns the object which is the event's source. If you have a handful of JButtons, and you don't know which one was the source, it is very common to check each one against the getSource() method using ==. Another example is comparing Enums, although those are often done in switch statements.
    But in the case of Strings, == can be deceiving due to the literal pool.

    Most people advise using literals to initiate Strings. There are apparently advantages to using the construct for programs which require synchronization, but I've never personally ran into any issues here.
    The constructor is needed if you want to a unique String value which is not referring to the literal String pool. Some people have mentioned this in the String.substring() method, since apparently all that does is adjust the starting index value in the String object, so all the characters which you thought you got rid of with the substring method apparently still exist in the String object. But it is debatable whether or not this even matters.
    But these are very odd examples. In 99.99% of java programming you'll do, initializing with literals should be fine.
    NOTE TO NEW PEOPLE LOOKING FOR HELP ON FORUM:

    When asking for help, please follow these guidelines to receive better and more prompt help:
    1. Put your code in Java Tags. To do this, put [highlight=java] before your code and [/highlight] after your code.
    2. Give full details of errors and provide us with as much information about the situation as possible.
    3. Give us an example of what the output should look like when done correctly.

    Join the Airline Management Simulation Game to manage your own airline against other users in a virtual recreation of the United States Airline Industry. For more details, visit: http://airlinegame.orgfree.com/

  17. #17
    Junior Member
    Join Date
    Oct 2013
    Posts
    11
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Comparison of Objects and such

    Thanks. It was very good and in depth discussion.

    I really appreciate the views given by you that make my concept more clear.

    Thanks a lot

Similar Threads

  1. quicksort and bubblesort comparison
    By husain2213 in forum What's Wrong With My Code?
    Replies: 7
    Last Post: March 25th, 2013, 05:51 AM
  2. Why is comparison of objects of Class implementing CharSequence undefined?
    By rsameera in forum Object Oriented Programming
    Replies: 1
    Last Post: September 4th, 2011, 02:30 PM
  3. table comparison
    By awecode in forum JDBC & Databases
    Replies: 2
    Last Post: October 12th, 2010, 09:37 AM
  4. Need help with array comparison
    By raidcomputer in forum Collections and Generics
    Replies: 4
    Last Post: November 17th, 2009, 01:55 PM
  5. Array comparison
    By subhvi in forum Collections and Generics
    Replies: 5
    Last Post: September 3rd, 2009, 03:56 AM