0
public static void main(String[] args){

/* lots of codes */

    if(profile.addFriend(buffernametwo)){
      boolean a = profile.addFriend(buffernametwo);
      System.out.println(a); 
     //prints false; however if I directly put profile.addFriend(buffernametwo) 
     //and follow the debugger, it will appear true

      /* lots of codes */

    }
/* lots of codes */

//the following method is in a different class

public boolean addFriend(String friend) {

        for(int i = 0;i < profile_friend.size();i++){
        //Here is the point
            if(friend == profile_friend.get(i)){
                return false;
            }
        }
        profile_friend.add(friend);
        return true;

/* lots of codes */

private ArrayList<String> profile_friend = new ArrayList<String>();

}

The question is in the comment of the code

cdeszaq
  • 30,869
  • 25
  • 117
  • 173

2 Answers2

3

There is a String pool in Java so here they coincidentaly have the same reference. But you shouldn't rely on this and always use equals() when comparing Strings.

Jan Zyka
  • 17,460
  • 16
  • 70
  • 118
0

Because the == compares the references and both abc and bcd are pointing to two same memory location. equals() function suggested by @jan Zyka is the correct option to compare two different strings.

However if you intentionally want that both the abc and bcd should point the same memory location, You can use intern() method of String class... read documentation here.

Amit
  • 13,134
  • 17
  • 77
  • 148
  • 1
    His two intances in the example already have same memory location. That is what surprised him. – Jan Zyka Jan 05 '12 at 09:23
  • yea, but unfortunately that is not true across JVM implementations. If someone intentionally want to share the memory address along Sting references than the ideal way will be to use intern()... – Amit Jan 05 '12 at 09:32
  • 1
    @amit there's no need to intern string constants, it's automatic and required by the JLS. – Alnitak Jan 05 '12 at 09:37
  • OK, i put my original code in the box. Please help me out. thx – Robin Banner Jan 05 '12 at 09:54