Java Examples - Concatenate Strings


Advertisements


Problem Description

How to optimize string concatenation ?

Solution

Following example shows performance of concatenation by using "+" operator and StringBuffer.append() method.

public class StringConcatenate {
   public static void main(String[] args) {
      long startTime = System.currentTimeMillis();
      
      for(int i = 0;i<5000;i++) {
         String result = "This is"
            + "testing the"
            + "difference"+ "between"
            + "String"+ "and"+ "StringBuffer";
      }
      long endTime = System.currentTimeMillis();
      System.out.println("Time taken for string" 
         + "concatenation using + operator : " 
         + (endTime - startTime)+ " ms");
      long startTime1 = System.currentTimeMillis();
      
      for(int i = 0;i<5000;i++) {
         StringBuffer result = new StringBuffer();
         result.append("This is");
         result.append("testing the");
         result.append("difference");
         result.append("between");
         result.append("String");
         result.append("and");
         result.append("StringBuffer");
      }
      long endTime1 = System.currentTimeMillis();
      System.out.println("Time taken for String concatenation" 
         + "using StringBuffer : "
         + (endTime1 - startTime1)+ " ms");
   }
}

Result

The above code sample will produce the following result. The result may vary.

Time taken for stringconcatenation using + operator : 0 ms
Time taken for String concatenationusing StringBuffer : 22 ms

Problem Description

How to do string concatenation ?

Solution

Following example shows concatenation string. This method returns a String with the value of the String passed into the method, appended to the end of the String, used to invoke this method.

public class HelloWorld { 
   public static void main(String []args) {
      String s = "Hello"; 
      s = s.concat("word");
      System.out.print(s);
   }
}

Result

The above code sample will produce the following result. The result may vary.

Helloword

java_strings.htm

Advertisements