Friday, 5 July 2019

JAVA StringBuffer and StringBuilder object conversion to String


We can convert a StringBuffer or StringBuilder object  to String by using toString() method of Object class.
StringConversion.java
class StringConversion
{
          public static void main(String[] args)
          {
                   StringBuffer sb1=new StringBuffer("Silan");
                   StringBuilder sb2=new StringBuilder("Technology");
                   String s1=sb1.toString();
                   String s2=sb2.toString();
                   System.out.println(s1+" "+s2);
          }
}
Output:
Silan Technology


StringConversion1.java
class StringConversion1
{
          public static void main(String[] args)
          {
                   StringBuffer sb1=new StringBuffer("Silan");
                   StringBuffer sb2=new StringBuffer("Silan");
                   String s1=sb1.toString();
                   String s2=sb2.toString();
                   if(s1.equals(s2))
                   {
                             System.out.println("s1 and s2 contents are equal");
                   }
                   else
                   {
                             System.out.println("s1 and s2 contents are not equal");
                   }
          }
}
Output:
s1 and s2 contents are equal

No comments:

Post a Comment