Rabu, 07 Januari 2015

3 Examples to Concatenate String in Java



String concatenation is the process of joining two or more small String to create a big String. For example you can create full name by concatenating first and last name of a person. Java provides multiple ways to concatenate String, but the easiest of them is by using + operator. It is one of the magical operator in Java, though Java doesn't support operator overloading, it has made an exception in case of String and + operator.  Plus operator is a binary operator and primarily used to add two numbers if both operands are integer but it can also used to concatenate String if either both or first operand is String. For example "Java" + "Programming" will produce "JavaProgramming". You can use this operator even to convert integer to String in Java by concatenating an empty String with an integer. For example  "" + 123 will produce String "123".  Other two ways to concatenate String in Java is by using StringBuffer and StringBuilder. Both these classes are mutable counterpart of String class and used to modify mutable String. Since String is Immutable in Java, any operation on String, including concatenation always produce a new String object. If you use Plus operator to concatenate String in a loop, you will end up with lots of small String object which can fill up your heap and can create lot of work for your garbage collector. To avoid such issues, Java designers have provided StringBuffer and StringBuilder, both of which can be used to create mutable String which will not produce a new String object if you do concatenation. There is one more method to concatenate String in Java is by using String.concat() function. You can use this one for String concatenation.










4 Ways to concatenate String in Java


As explained in first paragraph, there are three main ways to concatenate String in Java :




  1. Concatenation operator (+)

  2. StringBuffer class

  3. StringBuilder class

  4. String.concat() function




Let's  see examples of each way to concatenate two String object in Java.








String concatenation using + Operator


This is the most simple way to do the job. For example "One" + "Two" will produce a String object "OneTwo". You can use this operator to combine more than one String e.g. two, three, four or any number of String object like "abc" + "def" +  "ghi" +  "jklm" will result in "abcdefghijklm". You can also use String literal or String variable, it will work in both scenario. Most important thing to remember about doing String concatenation is that it doesn't modify any String object and always create a new String object. If you use literal or if the object is already exists in pool, then it may return object from String pool but otherwise it will result in a new String object. Never use this method while concatenating String in loop, it will result in lots of small String garbage. Also don't forget to store the reference of object returned by + operator.  You can also use this method to convert int to String in Java, provided they are always the second operand.










Concatenate String using StringBuffer and StringBuilder class


This is right way to join multiple String in Java. Why? because it represent a mutable String and when you concatenate multiple small String, it won't generate temporary intermediate String object. This result in lot of memory saving and reduce garbage collection time. By the way, you should always use StringBuilder instead of StringBuffer because it provides the same functionality but without any synchronization overhead, which means faster operation. Use of StringBuffer or StringBuilder also results in fluent and readable code as shown below :



String result = new StringBuilder(14).append(firstname).append(" ").append(lastname).toString();



You can see that how easy is to join multiple String using StringBuilder. By the way don't forget to initialize StringBuilder with required capacity which is equal to number of characters in final String. This will save memory by utilizing object properly and reduce CPU time spent during re-sizing of StringBuilder.










Java Program to Concatenate String in Java


Here is our sample Java program which will show you how you can use these three ways to concatenate String in Java. In first example, we have used + operator, while in second and third example we have used StringBuilder and StringBuffer class to join Strings in Java.



/**
* Java program to show how to concatenate String in Java.
* Easiest way is by using + operator, "abc" + "def" will
* produce a new concatenated String "abcdef"
*
* @author WINDOWS 8
*/


public class StringConcat{

public static void main(String args[]) {

String firstname = "Virat";
String lastname = "Kohli";

// 1st way - Use + operator to concatenate String
String name = firstname + " " + lastname;
System.out.println(name);


// 2nd way - by using StringBuilder
StringBuilder sb = new StringBuilder(14);
sb.append(firstname).append(" ").append(lastname);
System.out.println(sb.toString());


// 3rd way - by using StringBuffer
StringBuffer sBuffer = new StringBuffer(15);
sBuffer.append(firstname).append(" ").append(lastname);
System.out.println(sBuffer.toString());

}

}

Output
Virat Kohli
Virat Kohli
Virat Kohli











Performance of String concatenation in Java



As I told you the quickest way of concatenating String in Java is by using  concatenation operator ("+")  and it works quite well if you just have to join one or two fixed size String, but if you have to join thousands of String or you are performing String concatenation in loop then performance of concatenation operator is not good. Main reason of performance drop is creation of lots of temporary String object due to immutability of String. If you are doing lot of String concatenation in your Java application and concern how different ways will perform, I would suggest you to read this article, which compares performance of concatenation operator, String.concat() function, StringBuilder and StringBuffer using Perf4j. You can see with results that it confirms the theory that for large scale of String concatenation StringBuilder is the best approach. For your information, following String concatenation performance benchmark is from 64-bit OS (Windows 7), 32-bit JVM (7-ea), Core 2 Quad CPU (2.00 GHz) with 4 GB RAM, so it's quite relevant.





4 Examples of String concatenation in Java









That's all about how to concatenate String in Java. We have leaned how we can use Plus operator +, StringBuffer and StringBuilder to join multiple String literal or object to produce a new bigger String. Just remember that String concatenation using + operator is also converted to corresponding StringBuffer and StringBuilder call depending upon which version of Java you are using because StringBuilder is only available from Java 1.5.  Few key things you should remember :




  • Don't use + operator for String concatenation in loop.

  • Always use StringBuilder for concatenation of multiple String.

  • Always initialize StringBuilder with proper capacity.






Thanks a lot for reading this far, if you like this article then don't forget to check other String related posts as well like :




  1. Why character array is better than String for storing password? (read here)

  2. Best way to check if String is empty in Java? (see here)

  3. Why String is final in Java? (read here)

  4. Difference between StringBuffer and StringBuilder in Java? (read here)

  5. Why use equals() to compare String in Java? (check here)

























Source:http://javarevisited.blogspot.com/2015/01/3-examples-to-concatenate-string-in-java.html

1 komentar:

  1. Nice explanation with examples.
    Thanks,
    https://www.flowerbrackets.com/difference-between-equal-operator-vs-equals-method-java/

    BalasHapus