Skip to Main Content

New to Java

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

Effective value comparison of StringBuilder objects

763890Jan 27 2010 — edited Jan 28 2010
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");
		}
	}

}
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Feb 25 2010
Added on Jan 27 2010
7 comments
825 views