Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Sting Builder vs String Buffer in java

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 726
    Comment on it

    We know that Strings are immutable or constants but String builder and String buffer are basically used to provide dynamic implementation of Strings.

    But String Builder is not thread safe that means more than one process can access or modify the same String builder object but String buffer is synchronized in nature.

    As well as the speed of String Builder is more than String buffer.

    Example :

    public class Ex {
    
        public static void main(String[] args){
    
            long startTime = System.currentTimeMillis();
            StringBuilder stringBuilder = new StringBuilder("name");
            for (int i = 0; i < 1000; i++) {
                stringBuilder.append(i+"");
            }
    
            System.out.println("time taken by string builder = " + (System.currentTimeMillis()-startTime) + " ms");
    
            StringBuffer stringBuffer = new StringBuffer("name");
            for (int i = 0; i < 1000; i++) {
                stringBuffer.append(i+"");
            }
    
            System.out.println("time taken by string buffer = " + (System.currentTimeMillis()-startTime)+ " ms");
    
        }
    
    }
    

    Output :

    time taken by string builder = 3 ms
    time taken by string buffer = 7 ms

     

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: