Possible Duplicate:
How do I compare strings in Java?
Demonstrating string comparison with Java
I am getting confused by the very basics here. Since I've started using java I was always told "do not use == for string comparison; always use equals". Now I've started learning for the OCJP and came across some confusing points.
1)
String s1 = "Monday";
String s2 = "Monday";
s1 == s2 returns true;
2) Let's say a have a class defined as follows:
class Friend {
String name;
Friend(String n){
this.name = n;
}
public boolean equals(Object o){
return ((Friend) o).name == this.name;
}
}
and I create instances of two objects:
Friend f1 = new Friend("1");
Friend f2 = new Friend("1");
f1.equals(f2)
will return true
3) Finally, I have MyClass with main method defined:
public static void main(String[] args) {
System.out.println(args[0] == "x");
}
After the invocation java MyClass x
false will be printed.
What is the difference between 1, 2 and 3? Why isn't false returned in case 1 and 2, when two strings obviously refer to different objects?