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

2 comments:

  1. Great article! Very helpful for readers looking for clear insights. For those interested in skill development, check out best training institute in Chennai offering quality courses. Helpful information about best guest posting sites.

    ReplyDelete
  2. Great article! Very helpful for readers looking for clear insights. For those interested in skill development, check out best training institute in Chennai offering quality courses. Helpful information about best guest posting sites.

    ReplyDelete