String vs StringBuilder vs StringBuffer in Java ?

Total Post:113

Points:791
Java 
 278  View(s)
Ratings:
Rate this:

String vs StringBuilder vs StringBuffer in Java ?

  1. Post:140

    Points:984
    Re: String vs StringBuilder vs StringBuffer in Java ?

    class mindstick

       // Concatenates to String
        public static void concat1(String s1)
        {
            s1 = s1 + "mindstick";
        }
        // Concatenates to StringBuilder
        public static void concat2(StringBuilder s2)
        {
            s2.append("mindstick");
        }
        // Concatenates to StringBuffer
        public static void concat3(StringBuffer s3)
        {
            s3.append("mindstick");
        }
        public static void main(String[] args)
        {
            String s1 = "mind";
            concat1(s1); // s1 is not changed
            System.out.println("String: " + s1);
            StringBuilder s2 = new StringBuilder("mind");
            concat2(s2); // s2 is changed
            System.out.println("StringBuilder: " + s2);
            StringBuffer s3 = new StringBuffer("mind");
            concat3(s3); // s3 is changed
            System.out.println("StringBuffer: " + s3);
        }
    }

    From String to StringBuffer and StringBuilder : 

    directly pass String class object to StringBuffer and StringBuilder in class constructors. 

    public class Test  
    {
        public static void main(String[] args)
        {
            String str = "mindstick";
            // conversion from String object to StringBuffer
            StringBuffer sbr = new StringBuffer(str);
            sbr.reverse();
            System.out.println(sbr);
            // conversion from String object to StringBuilder
            StringBuilder sbl = new StringBuilder(str);
            sbl.append("software");
            System.out.println(sbl);
        }
    }

Answer

Please check, If you want to make this post sponsored

You are not a Sponsored Member. Click Here to Subscribe the Membership.