String concatenation in java 8

27/09/2016 Amit Gupta 324 Java

In this article, we will understand the newly added method in String class i.e. join method which is used for string concatenation in Java.

Before Java 8, we all have been using either "+" operator or "concat()" method of String class or "append()" method of StringBuffer/StringBuilder class to append strings in Java. Java 8 came up with new method i.e. "join()" method in String class which can be used to append strings in Java.

 public static String join(CharSequence delimiter, CharSequence... elements)

This method returns a new String composed of copies of the CharSequence elements joined together with a copy of the specified delimiter.

Let us understand the underlying implementation of join() method -

String#join()

public static String join(CharSequence paramCharSequence, CharSequence[] paramArrayOfCharSequence) {
		Objects.requireNonNull(paramCharSequence);
		Objects.requireNonNull(paramArrayOfCharSequence);

		StringJoiner localStringJoiner = new StringJoiner(paramCharSequence);
		for (CharSequence localCharSequence : paramArrayOfCharSequence) {
			localStringJoiner.add(localCharSequence);
		}
		return localStringJoiner.toString();
}

StringJoiner#add()

public StringJoiner add(CharSequence paramCharSequence) {
		prepareBuilder().append(paramCharSequence);
		return this;
}

StringJoiner#prepareBuilder()

private StringBuilder prepareBuilder() {
		if (this.value != null)
			this.value.append(this.delimiter);
		else {
			this.value = new StringBuilder().append(this.prefix);
		}
		return this.value;
}

As we know String is a immutable class each time a new object is created when we concat two string objects using + operator or "concat()" method. This can be avoided using join() method of String class. 

Example

import java.util.ArrayList;
import java.util.List;



/**
 * @author Amit Gupta
 *
 */
public class StringJoinerExample {

	public static void main(String[] args) {
		List stringList = new ArrayList<>();
		stringList.add("Java");
		stringList.add("J2EE");
		stringList.add("Spring");
		stringList.add("Hibernate");
		//join list of string with delimiter as ,(comma)
		System.out.println(String.join(",", stringList));
		
	}
}

Output

Java,J2EE,Spring,Hibernate

In this article, we learnt the usage of newly added method in String class i.e. join method which is used for string concatenation in Java.

Author
Author: Amit Gupta
Published On: 27/09/2016
Last revised On: 10/6/2016 11:47:37 PM
View all articles by Amit Gupta

Share this post

Comments

Comments
comments powered by Disqus

Navigation

Social Media