...in other words: let's suppose I have 2 Strings declared as so:
String one = new String("yay!");
String two = new String("yay!");
these two Strings are two different objects, but if I run
if(one.equals(two))
System.out.println("equals() returns true.");
I get "equals() returns true". This is because the String class overrides the equals() method to implement a content level equality. However, I need to access a reference level equality (like the one implemented in Object) to distinguish the object one form the object two. How can I do that?
I tried this:
one.getClass().getSuperclass().equals();
to try to invoke the Object equals() method of the String one but it didn't work.
Any advice?
If you want to check reference just perform:
one == two
But be careful with strings. There is a thing called String constant pool so they may refer to the same object.
String
in java uses a String Literal Pool
, this means is: "When you try construct a string, first String class search in Literal Pool
for traditional same string ,if exist return it, and if don't exist create it", so you can't check by equals
method compare refernce of String instance, you have to use ==
operator as following:
String one = new String("yay!");
String two = new String("yay!");
if(one.equals(two))
System.out.println("equals() returns true.");
if(one == two)
System.out.println(" == operator returns true.");
result is :
equals() returns true.
see following link for more information:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With