Possible Duplicates:
Java String.equals versus ==
whats the difference between ".equals and =="
public String getName() {
return new String("foobar");
}
if(getName() != "foobar2") {
//Never gets executed, it should, wtf!.
}
if(!getName().equals("foobar2")) {
//This works how it should.
}
So yeah my question is simple.. why doesn’t != behave the same as !equals() aka (not Equals).
I don’t see any logicial reason why one should fail, both are the same exact code in my mind, WTH.
Looking at java operators
http://download.oracle.com/javase/tutorial/java/nutsandbolts/operators.html
You can clearly see
equality == !=
are the equality operators, sure I usually use != only on numbers.. but my mind started wandering and why doesn’t it work for String?
EDIT:
Here’s something that looks more like the actual issue..
for (ClassGen cg : client.getClasses().values()) {
final ConstantPoolGen cp = cg.getConstantPool();
if(cp.lookupInteger(0x11223344) != -1) {
for (Method m : cg.getMethods()) {
System.out.println("lots of class spam");
if(m.getName() != "<init>") continue;
System.out.println("NEVER GETS HERE, 100% SURE IT HAS CONSTRUCTOR LOL");
}
}
}
A string is an Object, not a primitive.
==and!=compare two primitives to each other.To compare strings you need to loop trough each character and compare them in order which is what
.equals()does.If you do any OOP in Java you need to override equals when you want to do equality checks on the Objects, and implement Comparable and
.compare()if you want to be able to do things like sort them.Here is a quick example of equals:
Now a Person can be compared to another Person like:
Which will only return true if both people have the same name. You can define what makes two objects equal however you want, but objects are only
==if they are really just two pointers to the same object in memory.