Results 1 to 3 of 3
  1. #1
    AcousticBruce is offline Senior Member
    Join Date
    Dec 2010
    Location
    Indiana
    Posts
    202
    Rep Power
    4

    Default Understanding String vs new String()

    This is odd, but there must be a reason.


    This code returns "Does NOT"
    Java Code:
            String str1 = new String("String One");
            String str2 = new String("String One");
    
            if (str1 == str2) {
                System.out.println("Equals");
    
            } else {
                System.out.println("Does NOT");
            }

    This code returns "Equals"
    Java Code:
            String str1 = "String One";
            String str2 = "String One";
    
            if (str1 == str2) {
                System.out.println("Equals");
    
            } else {
                System.out.println("Does NOT";
            }

  2. #2
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    25

    Default

    == tests to see if the object referred to by one variable is the same object as that referred to by the other variable, and with Strings (and most other objects), you really don't care about this. What you want to know instead is are strings themselves, the characters, order of characters and case the same for one String vs another, and this is where equals(...) and equalsIgnoreCase(...) come in.

    You'll want to read up on the String pool too to find out why you're getting different results in your two cases above.

  3. #3
    jomypgeorge is offline Member
    Join Date
    May 2010
    Posts
    90
    Rep Power
    0

    Default

    when we assign a value to string variable compiler checks if it is already used in the same program. if it is used it assign same object to reference

    so
    String str1 = "hello";
    String str2 = "hello;

    is equivalent to

    String str1, str2;
    str1 = "hello";
    str2 = str1;
    both str1,str2 points to same object.

    but in the case of new operator it create new object of string with same value.

Similar Threads

  1. Replies: 12
    Last Post: 11-26-2010, 08:33 AM
  2. Replies: 1
    Last Post: 11-04-2010, 06:53 PM
  3. combine string[] into string like perl's join function
    By tekberg in forum Advanced Java
    Replies: 9
    Last Post: 02-23-2009, 01:05 PM
  4. Replies: 5
    Last Post: 01-11-2009, 10:12 AM
  5. Replies: 0
    Last Post: 11-20-2007, 04: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
  •