Hi there,
I got questions in comments of the code. Can anyone help?
public class StringBuilderTest {
public static void main(String[] args) {
StringBuilder sb = new StringBuilder("abc");
StringBuilder sb1 = new StringBuilder("abc");
// only if sb = sb1 returns true, coz different object referenced
if ( sb.equals(sb1)){
System.out.println("equal value");
}
/*
* I think the following blocks both return true as a result but the second
* block is better choice from a performance perspective.
* Am I right? or wrong?
*
* (hopefully, comparison at object level runs faster than char level)
*/
// two String objects are newly created and compared on char sequence basis
if ( sb.toString().contentEquals(sb1.toString())){
System.out.println("equal value");
}
// two String objects are newly created and compared on object basis
if ( sb.toString().equals(sb1.toString())){
System.out.println("equal value");
}
/*
* Overall, the following is the best practice to do the comparison because of
* reducing intermediate string object to one can improve performance
* Am I right? or wrong?
*
*/
// one String object is newly created and compared against StringBuilder object
// on char sequence basis
if (sb.toString().contentEquals(sb1)){
System.out.println("equal value");
}
}
}