Sunday 12 August 2012

Comparing String with StringBuilder in Java


This example shows how to compare String object with a StringBuilder object using equals and contentEquals  methods of the String class.



public class ComapreStringWithStringBuilder {
 public static void main(String args[]) {

  String str = "Java";
  StringBuilder strBuild = new StringBuilder(str);

  /**
   * String.equals method can be used only for comparing
   * two Strings,so first convert StringBuilder to String
   * using toString method and then compare.
   **/
  if (str.equals(strBuild.toString())) {
   System.out.println("String and StringBuilder contains" +
     " same data");
  }

  /**
   * boolean contentEquals(CharSequence cs) Compares this
   * string to the specified CharSequence. The result is
   * true if and only if this String represents the same
   * sequence of char values as the specified
   * sequence.
   **/

  if (str.contentEquals(strBuild)) {
   System.out.println("String and StringBuilder contains" +
     " same data");
  }
 }
}


The output is:


String and StringBuilder contains same data
String and StringBuilder contains same data

No comments:

Post a Comment