You have to use equals()
if(!foo.equals(bar))
But with, Stringyou can do the following, since the class has Stringimplemented the method equals().
String a = "hi";
String b = "hii";
if (a!=b){
System.out.println("yes");
}else {
System.out.println("no");
}
Conclusion:
yes
If you want to go your own way, you must override the method equals().
Example: With Override Canceled equals()
public class Test {
private String name;
private int age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
Now take a look at this
Test a = new Test();
Test b = new Test();
a.setAge(1);
a.setName("hi");
b.setAge(1);
b.setName("hi");
if (a!=b){
System.out.println("yes");
}else {
System.out.println("no");
}
Conclusion:
yes
Now you can see the same problem here.
source
share