Java String, StringBuffer And StringBuilder Difference

Java has three character sequence manipulation class. They are java.lang.String, java.lang.StringBuffer and java.lang.StringBuilder. The most popular used class maybe java.lang.String, but there are a lot of difference between them.

Introduction

  1. String is final and immutable. You can not modify a String object. When you modify it (such as trim it’s left or right white space, covert from lower case to upper case), JVM(Java Virtual Machine) will create a new Object for each action. So if there are a lot of String operations in your java code, there will left a lot of temporary garbage object. Because it is final so it is thread safe. The “+” operator for add two or more String object is implemented using either StringBuilder or StringBuffer by JVM in java.
  2. StringBuffer is a mutable class. You can modify it’s data at any time. JVM will not create extra object when you operate data in it. So it is more efficient than String. It is also thread safe because all it’s public method are synchronized so two or more threads can not execute it’s method at the same time. It can be converted to String by it’s toString() method.
  3. StringBuilder is introduced in JDK 5. It behaves like StringBuffer, but the most difference is that all it’s public method is not synchronized. So it is not thread safe but it is more faster than StringBuffer. Two or more thread can execute it’s method at the same time. Therefor you should consider synchronization issue when you use it in multiple thread java environment.

Difference Between Them

  1. String object can not be modified. The other two can be modified.
  2. StringBuilder is not thread safe. The other two are thread safe.
  3. “+” operator for String concatenating is implemented use either StringBuilder or StringBuffer.
  4. StringBuilder perform more faster than StringBuffer.
  5. StringBuffer perform more faster than String.

Code Example

  1. String Example
    	private void stringExample()
    	{
    		String str1 = "good ";
    		
    		String str2 = "morning  ";
    				
    		str2 = str1 + str2;
    		
    		System.out.println(str2);
    		
    		System.out.println(str2.toUpperCase());
    		
    		
    		System.out.println(str2.trim());
    	}

    Output

    good morning  
    GOOD MORNING  
    good morning
  2. StringBuffer Example
    	private void stringBufferExample()
    	{
    		StringBuffer strBuf = new StringBuffer();
    		
    		strBuf.append("You ");
    		
    		strBuf.append(" are welcome ");
    		
    		strBuf.append(" to Java world ");
    
    		System.out.println(strBuf.toString().trim());
    	}

    Output

    You  are welcome  to Java world
  3. StringBuilder Example
    	private void stringBuilderExample()
    	{
    		StringBuilder strBuilder = new StringBuilder();
    		
    		strBuilder.append("Hello ");
    		
    		strBuilder.append(" Java World ");
    
    		System.out.println(strBuilder.toString().trim());
    	}

    Output

    Hello  Java World
  4. Performance Compare
    	/*
    	 * Test how much time that each class will cost for same repeat time operation.
    	 * */
    	private void performanceTest()
    	{
    		/* All operation repeat same count.*/
    		int repeatCount = 100000; 
            
    		/* Test StringBuffer */
    		long beginTime = System.currentTimeMillis();
    		StringBuffer sb = new StringBuffer("dev2qa.com is");  
    		for (int i=0; i<repeatCount; i++){  
    			sb.append("Java tutorial ");  
    		}  
    		System.out.println("StringBuffer cost time: " + (System.currentTimeMillis() - beginTime) + "ms");  
            
            /* Test StringBuilder */
            beginTime = System.currentTimeMillis();  
            StringBuilder sb2 = new StringBuilder("dev2qa.com is");  
            for (int i=0; i<repeatCount; i++){  
                sb2.append("java tutorial");  
            }  
            System.out.println("StringBuilder cost time: " + (System.currentTimeMillis() - beginTime) + "ms");  
            
            /* Because it is too slow so put the java code at the end of this method.
             * After run below java code, there will have about repeatCount garbage object left in jvm.
             * */
            beginTime = System.currentTimeMillis(); 
    		String str = "dev2qa.com is";  
    		for (int i=0; i<repeatCount; i++){  
                str += "Java tutorial ";  
            }  
            System.out.println("String cost time: " + (System.currentTimeMillis() - beginTime) + "ms");  
    	}

    Output

    StringBuffer cost time: 12ms
    StringBuilder cost time: 6ms
    String cost time: 33267ms

[download id=”1489″]

1 thought on “Java String, StringBuffer And StringBuilder Difference”

  1. StringBuffer is synchronized as well as Thread safe so can be used in multithreading. StringBuilder is not synchronized as well as thread safe. Many thanks for sharing this.

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.