class strb
{
static public void main(String...string)
{
StringBuilder s1 = new StringBuilder(\"Test\");
StringBuilder s2 = new StringBuild
StringBuilder
class doesn't have the implementation of equals()
method like one in the String
class.
So it executes default Object class functionality, which again checks only for address equivalency, which is not same in this case. so it prints false.
Note 1: You can use ==
operator on objects also, but it simply checks if the address of both the objects are same or not.
Note 2: ==
operator plays good role in comparing two String objects created in string constant pool, to find out if it is really creating a new object in string constant pool or not.
StringBuilder
and StringBuffer
not override the equals function of Object
class.but string override the equals
method.
the function of Object
is this
public boolean equals(Object obj) {
return (this == obj);
}
you could write your code like this.
System.out.println(s1.toString() == s2.toString());
System.out.println(s1.toString().equals(s2.toString()));
Agreed with both of the above responses, but I'm worth noting to actually compare contents you can do:
System.out.println(s1.toString().equals(s2.toString())); //Line 1
Check the contract of equals
method:
it must be consistent (if the objects are not modified, then it must keep returning the same value).
That's why StringBuilder does not override it regardless of its content.
Let's take example above.
StringBuilder s1 = new StringBuilder("Test");
StringBuilder s2 = new StringBuilder("Test");
Maybe, to you it is expected that s1.equals(s2)
returns true
due to current run time values.
But what about if you change add line:
s1.append("abc");
Then s1 and s2 will have different string contents and s1.equals(s2)
is expected to be false
. But it is in contradiction with consistency.
The StringBuilder
class does not provide an overriden equals()
method. As such, when that method is called on an instance of StringBuilder
, the Object
class implementation of the method is executed, since StringBuilder extends Object
.
The source code for that is
public boolean equals(Object obj) {
return (this == obj);
}
Which simply compares reference equality.
for your first answer check @abmitchell 's Answer
And for your Edit:
In Java, String is an object and we can't compare objects for value equality by using ==
==
is used for comparing primitives values or object references.
To compare Object values we use equals()
in Java