Sunday 12 August 2012

Comparing String with StringBuffer in Java


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


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

  String str = "Java";
  StringBuffer strBuff = new StringBuffer(str);

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

  /**
   * boolean contentEquals(StringBuffer sb) - Compares this
   * string to the specified StringBuffer. The result is true
   * if and only if this String represents the same sequence
   * of characters as the specified StringBuffer.
   **/
  if (str.contentEquals(strBuff)) {
   System.out.println("String and StringBuffer contains" +
     " same data");
  }
 }
}


The output is:


String and StringBuffer contains same data
String and StringBuffer contains same data

No comments:

Post a Comment