Results 1 to 4 of 4
  1. #1
    Join Date
    Oct 2003
    Posts
    138

    Unanswered: When String objects are compared with == and Strings contain the same values, the res

    When String objects are compared with == and Strings contain the same values, the result is TRUE or FALSE?

  2. #2
    Join Date
    Jan 2004
    Location
    Sochaux (France)
    Posts
    55

    Re: When String objects are compared with == and Strings contain the same values, the res

    Originally posted by valexena
    When String objects are compared with == and Strings contain the same values, the result is TRUE or FALSE?
    you cannot compare strings with '=='.
    You have to use the equals() method.
    If you use ==, the result will be true if the two strings are pointer on the same element.
    But not the contents of the string :
    eg :
    String a = "toto";
    String b = "toto";

    a.equals(b) => TRUE
    a == b => FALSE

  3. #3
    Join Date
    Feb 2004
    Posts
    18

    Re: When String objects are compared with == and Strings contain the same values, the res

    Originally posted by venderic
    you cannot compare strings with '=='.
    You have to use the equals() method.
    If you use ==, the result will be true if the two strings are pointer on the same element.
    But not the contents of the string :
    eg :
    String a = "toto";
    String b = "toto";

    a.equals(b) => TRUE
    a == b => FALSE
    Hi,
    For the eg :
    String a = "toto";
    String b = "toto";

    a.equals(b) => TRUE
    a == b => TRUE

    However for the following
    String a = ("toto");
    String b = new("toto");

    a.equals(b) => TRUE
    a == b => FALSE


    In this case both are true. This is because of the way that Java handles Strings. Whenever you create a String using the method as shown in the first example then a String pool is searched. If the same String already exists in the pool then it will point to the same object, hence a==b will be true. However if you create a String using new then they will be pointing to different objects hence a==b is false.

  4. #4
    Join Date
    Oct 2003
    Posts
    138
    Now it is clear.
    Thank you,
    -valexena.

Posting Permissions

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